diff --git a/src/index.ts b/src/index.ts index a0db0f7..907b2c9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -278,7 +278,7 @@ export function render(tree?: Node | Node[], options: Options = {}): string { function makeAttr(key: string, attrValue: string | number | boolean, quoteStyle = 1): string { if (quoteStyle === 1) { // Single Quote - return ` ${key}='${attrValue}'`; + return makeSingleQuotedAttr(key, attrValue); } if (quoteStyle === 2) { @@ -288,9 +288,19 @@ export function render(tree?: Node | Node[], options: Options = {}): string { // Smart Quote if (typeof attrValue === 'string' && attrValue.includes('"')) { - return ` ${key}='${attrValue}'`; + return makeSingleQuotedAttr(key, attrValue); } return ` ${key}="${attrValue}"`; } + + function makeSingleQuotedAttr(key: string, attrValue: string | number | boolean): string { + // A `'` can't appear inside single quotes, + // so such values are double-quoted with `"` escaped instead. + if (typeof attrValue === 'string' && attrValue.includes('\'')) { + return ` ${key}="${attrValue.replace(/"/g, '"')}"`; + } + + return ` ${key}='${attrValue}'`; + } } diff --git a/test/test-core.spec.ts b/test/test-core.spec.ts index c9e59e4..657b3e1 100644 --- a/test/test-core.spec.ts +++ b/test/test-core.spec.ts @@ -133,6 +133,18 @@ test('{Attrs} {String} (json)', t => { t.is(render(fixture), expected); }); +test('{Attrs} {String} (json with apostrophe)', t => { + const fixture = { + attrs: { + 'x-data': '{"a":"it\'s"}', + }, + }; + + const expected = '
'; + + t.is(render(fixture), expected); +}); + test('{Content} {String}', t => { const fixture = {content: 'Hello world!'}; const expected = '