Skip to content

Commit

Permalink
Merge pull request #122 from lamplightdev/main
Browse files Browse the repository at this point in the history
Fixes #62 - Escape double quotes in attribute values
  • Loading branch information
taoqf committed May 22, 2021
2 parents 6434743 + e9ec888 commit e4e8116
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/nodes/html.ts
Expand Up @@ -119,6 +119,20 @@ export default class HTMLElement extends Node {
* Node Type declaration.
*/
public nodeType = NodeType.ELEMENT_NODE;

/**
* Quote attribute values
* @param attr attribute value
* @returns {string} quoted value
*/

private quoteAttribute(attr: string) {
if (attr === null) {
return "null";
}

return JSON.stringify(attr.replace(/"/g, '"'));
}
/**
* Creates an instance of HTMLElement.
* @param keyAttrs id and class attribute
Expand Down Expand Up @@ -708,7 +722,7 @@ export default class HTMLElement extends Node {
}
// Update rawString
this.rawAttrs = Object.keys(attrs).map((name) => {
const val = JSON.stringify(attrs[name]);
const val = this.quoteAttribute(attrs[name]);
if (val === 'null' || val === '""') {
return name;
}
Expand Down Expand Up @@ -739,7 +753,7 @@ export default class HTMLElement extends Node {
if (val === 'null' || val === '""') {
return name;
}
return `${name}=${JSON.stringify(String(val))}`;
return `${name}=${this.quoteAttribute(String(val))}`;

}).join(' ');
}
Expand Down
31 changes: 31 additions & 0 deletions test/quoteattributes.js
@@ -0,0 +1,31 @@
const { parse } = require('../dist');

// https://github.com/taoqf/node-html-parser/issues/62
describe('quote attributes', function () {
it('escapes double quotes when using setAttribute', function () {
const root = parse(`<div></div>`);
const div = root.firstChild;
div.setAttribute('foo', '[{"bar":"baz"}]');
div
.toString()
.should.eql('<div foo="[{&quot;bar&quot;:&quot;baz&quot;}]"></div>');
});

it('escapes double quotes when using setAttributes', function () {
const root = parse(`<div></div>`);
const div = root.firstChild;
div.setAttributes({ foo: '[{"bar":"baz"}]' });
div
.toString()
.should.eql('<div foo="[{&quot;bar&quot;:&quot;baz&quot;}]"></div>');
});

it('parses attributes containing &quot;', function () {
const root = parse('<div foo="[{&quot;bar&quot;:&quot;baz&quot;}]"></div>');
const div = root.firstChild;
div.getAttribute('foo').should.eql('[{"bar":"baz"}]');
div.attributes.should.eql({
foo: '[{"bar":"baz"}]',
});
});
});

0 comments on commit e4e8116

Please sign in to comment.