Skip to content

Commit 1f8cede

Browse files
committed
Parse and stringify comments
1 parent eadaed1 commit 1f8cede

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

lib/parse-tag.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,18 @@ module.exports = function (tag) {
3838
res.voidElement = true;
3939
}
4040

41+
if (res.name === '!--') { // comment tag
42+
res = {
43+
type: 'comment',
44+
};
45+
res.comment = '';
46+
var end = tag.indexOf('-->');
47+
if (end !== -1) {
48+
var comment = tag.slice(4, end);
49+
res.comment = comment;
50+
}
51+
return res;
52+
}
4153
}
4254

4355
var reg = new RegExp(attrRE);

lib/stringify.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ function stringify(buff, doc) {
1919
return buff;
2020
}
2121
return buff + doc.children.reduce(stringify, '') + '</' + doc.name + '>';
22+
case 'comment':
23+
buff += '<!--' + doc.comment + '-->';
24+
return buff;
2225
}
2326
}
2427

test/parse.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,39 @@ test('parse', function (t) {
5252
}]);
5353
t.equal(html, HTML.stringify(parsed));
5454

55+
html = '<!-- just a comment node -->';
56+
parsed = HTML.parse(html);
57+
t.deepEqual(parsed, [{
58+
type: 'comment',
59+
comment: ' just a comment node '
60+
}]);
61+
t.equal(html, HTML.stringify(parsed));
62+
63+
html = '<div><h2>Comment below this header</h2><!-- just a comment node --></div>';
64+
parsed = HTML.parse(html);
65+
t.deepEqual(parsed, [{
66+
name: 'div',
67+
type: 'tag',
68+
attrs: {},
69+
voidElement: false,
70+
children: [{
71+
attrs: {},
72+
name: 'h2',
73+
type: 'tag',
74+
voidElement: false,
75+
children: [{
76+
content: 'Comment below this header',
77+
type: 'text'
78+
}]
79+
},
80+
{
81+
type: 'comment' ,
82+
comment: ' just a comment node ',
83+
}]
84+
}]);
85+
t.equal(html, HTML.stringify(parsed));
86+
87+
5588
html = '<div>oh <strong>hello</strong> there! How are <span>you</span>?</div>';
5689
parsed = HTML.parse(html);
5790

0 commit comments

Comments
 (0)