From 6f6c824df54fa53af47956048b42ea47cd3b53bf Mon Sep 17 00:00:00 2001 From: taoqf Date: Thu, 17 Aug 2023 17:53:17 +0800 Subject: [PATCH] fix: #218 --- src/nodes/html.ts | 4 ++-- test/tests/issues/218.js | 46 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 test/tests/issues/218.js diff --git a/src/nodes/html.ts b/src/nodes/html.ts index 5708e33..6d60587 100644 --- a/src/nodes/html.ts +++ b/src/nodes/html.ts @@ -158,7 +158,7 @@ export default class HTMLElement extends Node { return 'null'; } - return JSON.stringify(attr.replace(/"/g, '"')).replace(/\\t/g, '\t').replace(/\\n/g, '\n').replace(/\\r/g, '\r'); + return JSON.stringify(attr.replace(/"/g, '"')).replace(/\\t/g, '\t').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\/g, ''); } /** @@ -713,7 +713,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 === undefined || val === 'null') { return name; } diff --git a/test/tests/issues/218.js b/test/tests/issues/218.js new file mode 100644 index 0000000..f5bada0 --- /dev/null +++ b/test/tests/issues/218.js @@ -0,0 +1,46 @@ +const { parse } = require('@test/test-target'); + +describe('issue 218', function () { + it('attribute value contains quote should be parsed correct', function () { + const html = ` +
nochange
+
expected
+
actual
+`; + const root = parse(html); + root.toString().should.eql(` +
nochange
+
expected
+
actual
+`); + root.querySelector('#e').setAttribute('onClick', "alert('hello')"); + + root.toString().should.eql(` +
nochange
+
expected
+
actual
+`); + + // root.querySelector('#a').setAttribute('title', '"replaced"'); + root.querySelector('#a').removeAttribute('color'); // FIXME + + root.toString().should.eql(` +
nochange
+
expected
+
actual
+`); + root.querySelector('#a').setAttribute('title', '"replaced"'); + root.toString().should.eql(` +
nochange
+
expected
+
actual
+`); + }); + it('should escape newlines to html entities', function () { + const root = parse('

'); + const p = root.firstChild; + p.setAttribute('a', '1\n2'); + p.getAttribute('a').should.eql('1\n2'); + p.toString().should.eql('

'); + }); +});