Skip to content

Commit e4e8116

Browse files
authored
Merge pull request taoqf#122 from lamplightdev/main
Fixes taoqf#62 - Escape double quotes in attribute values
2 parents 6434743 + e9ec888 commit e4e8116

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

src/nodes/html.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,20 @@ export default class HTMLElement extends Node {
119119
* Node Type declaration.
120120
*/
121121
public nodeType = NodeType.ELEMENT_NODE;
122+
123+
/**
124+
* Quote attribute values
125+
* @param attr attribute value
126+
* @returns {string} quoted value
127+
*/
128+
129+
private quoteAttribute(attr: string) {
130+
if (attr === null) {
131+
return "null";
132+
}
133+
134+
return JSON.stringify(attr.replace(/"/g, '"'));
135+
}
122136
/**
123137
* Creates an instance of HTMLElement.
124138
* @param keyAttrs id and class attribute
@@ -708,7 +722,7 @@ export default class HTMLElement extends Node {
708722
}
709723
// Update rawString
710724
this.rawAttrs = Object.keys(attrs).map((name) => {
711-
const val = JSON.stringify(attrs[name]);
725+
const val = this.quoteAttribute(attrs[name]);
712726
if (val === 'null' || val === '""') {
713727
return name;
714728
}
@@ -739,7 +753,7 @@ export default class HTMLElement extends Node {
739753
if (val === 'null' || val === '""') {
740754
return name;
741755
}
742-
return `${name}=${JSON.stringify(String(val))}`;
756+
return `${name}=${this.quoteAttribute(String(val))}`;
743757

744758
}).join(' ');
745759
}

test/quoteattributes.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
const { parse } = require('../dist');
2+
3+
// https://github.com/taoqf/node-html-parser/issues/62
4+
describe('quote attributes', function () {
5+
it('escapes double quotes when using setAttribute', function () {
6+
const root = parse(`<div></div>`);
7+
const div = root.firstChild;
8+
div.setAttribute('foo', '[{"bar":"baz"}]');
9+
div
10+
.toString()
11+
.should.eql('<div foo="[{&quot;bar&quot;:&quot;baz&quot;}]"></div>');
12+
});
13+
14+
it('escapes double quotes when using setAttributes', function () {
15+
const root = parse(`<div></div>`);
16+
const div = root.firstChild;
17+
div.setAttributes({ foo: '[{"bar":"baz"}]' });
18+
div
19+
.toString()
20+
.should.eql('<div foo="[{&quot;bar&quot;:&quot;baz&quot;}]"></div>');
21+
});
22+
23+
it('parses attributes containing &quot;', function () {
24+
const root = parse('<div foo="[{&quot;bar&quot;:&quot;baz&quot;}]"></div>');
25+
const div = root.firstChild;
26+
div.getAttribute('foo').should.eql('[{"bar":"baz"}]');
27+
div.attributes.should.eql({
28+
foo: '[{"bar":"baz"}]',
29+
});
30+
});
31+
});

0 commit comments

Comments
 (0)