File tree Expand file tree Collapse file tree 2 files changed +47
-2
lines changed Expand file tree Collapse file tree 2 files changed +47
-2
lines changed Original file line number Diff line number Diff line change @@ -119,6 +119,20 @@ export default class HTMLElement extends Node {
119
119
* Node Type declaration.
120
120
*/
121
121
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
+ }
122
136
/**
123
137
* Creates an instance of HTMLElement.
124
138
* @param keyAttrs id and class attribute
@@ -708,7 +722,7 @@ export default class HTMLElement extends Node {
708
722
}
709
723
// Update rawString
710
724
this . rawAttrs = Object . keys ( attrs ) . map ( ( name ) => {
711
- const val = JSON . stringify ( attrs [ name ] ) ;
725
+ const val = this . quoteAttribute ( attrs [ name ] ) ;
712
726
if ( val === 'null' || val === '""' ) {
713
727
return name ;
714
728
}
@@ -739,7 +753,7 @@ export default class HTMLElement extends Node {
739
753
if ( val === 'null' || val === '""' ) {
740
754
return name ;
741
755
}
742
- return `${ name } =${ JSON . stringify ( String ( val ) ) } ` ;
756
+ return `${ name } =${ this . quoteAttribute ( String ( val ) ) } ` ;
743
757
744
758
} ) . join ( ' ' ) ;
745
759
}
Original file line number Diff line number Diff line change
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="[{"bar":"baz"}]"></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="[{"bar":"baz"}]"></div>' ) ;
21
+ } ) ;
22
+
23
+ it ( 'parses attributes containing "' , function ( ) {
24
+ const root = parse ( '<div foo="[{"bar":"baz"}]"></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
+ } ) ;
You can’t perform that action at this time.
0 commit comments