Skip to content

Commit e2959d5

Browse files
authored
Merge pull request #5 from trusktr/for-of
fix comments, switch to for-of loop that appears to now work, fix attributes with `"` characters
2 parents 8289b1e + 5ecd8ff commit e2959d5

File tree

2 files changed

+11
-19
lines changed

2 files changed

+11
-19
lines changed

src/parse.js

+6-11
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@
44
const tagRE = /(?:<!--[\S\s]*?-->|<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>)/g;
55

66
// See https://regexr.com/6p8p0
7-
const attrRE = /(?:\s(?<boolean>[^/\s><=]+?)(?=[\s/>]))|(?:(?<name>\S+?)(?:\s*=\s*(?:(['"])(?<value1>[\s\S]*?)\3|(?<value2>[^\s>]+))))/g
7+
const attrRE = /(?:\s(?<boolean>[^/\s><=]+?)(?=[\s/>]))|(?:(?<name>\S+?)(?:\s*=\s*(?:(['"])(?<quotedValue>[\s\S]*?)\3|(?<unquotedValue>[^\s>]+))))/g
88
// ^ capture group 1: boolean attribute name (attributes without values)
9-
// ^ capture group 2: non-boolean attribue name
10-
// ^ capture group 4: non-boolean attribue value with quotes
11-
// ^ capture group 5: non-boolean attribue value without quotes
9+
// ^ capture group 2: non-boolean attribute name
10+
// ^ capture group 4: non-boolean attribute value with quotes
11+
// ^ capture group 5: non-boolean attribute value without quotes
1212
// TODO
1313
// - "/" values in the middle of the HTML tag (they don't self-close the element, but skipped)
1414
// - What other cases?
@@ -61,15 +61,10 @@ function parseTag(/**@type {string}*/tag) {
6161
}
6262
}
6363
}
64-
const reg = new RegExp(attrRE)
65-
const matches = tag.matchAll(reg)
66-
const matchesArray = Array.from(matches)
6764

68-
// for (const match of matches) {
69-
// for (const match of matchesArray) {
70-
for (let i = 0, l = matchesArray.length; i < l; i += 1) {
71-
const match = matchesArray[i]
65+
const reg = new RegExp(attrRE)
7266

67+
for (const match of tag.matchAll(reg)) {
7368
// TODO named groups method not working yet, groups is undefined in tests (maybe not out in Node.js yet)
7469
// const groups = match.groups
7570
// res.attrs[groups.boolean || groups.name] = groups.value1 || groups.value2 || ""

src/stringify.js

+5-8
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,18 @@
11
// Based on package html-parse-stringify2
22
// Expanded to handle webcomponents
33

4-
var attrString, stringifier;
5-
6-
attrString = function (attrs) {
7-
var buff, key;
8-
buff = [];
9-
for (key in attrs) {
10-
buff.push(key + '="' + attrs[key] + '"');
4+
function attrString(attrs) {
5+
const buff = [];
6+
for (const key in attrs) {
7+
buff.push(key + '="' + attrs[key].replace(/"/g, '&quot;') + '"');
118
}
129
if (!buff.length) {
1310
return '';
1411
}
1512
return ' ' + buff.join(' ');
1613
};
1714

18-
stringifier = function (buff, doc) {
15+
function stringifier(buff, doc) {
1916
switch (doc.type) {
2017
case 'text':
2118
return buff + doc.content;

0 commit comments

Comments
 (0)