Skip to content

Commit

Permalink
Fixes #62 - Escape double quotes in attribute values
Browse files Browse the repository at this point in the history
Currently double quotes (") are not escaped in attribute values causing those attributes not to be set correctly.

This commit replaces double quotes with `"`.
  • Loading branch information
lamplightdev committed May 20, 2021
1 parent 6434743 commit e9ec888
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 e9ec888

Please sign in to comment.