mirror of
https://github.com/markedjs/marked.git
synced 2026-11-30 16:48:05 +01:00
fix: keep a decoded character reference from forming a new one (#4111)
Since numeric references are decoded into the text token, a decoded "&", or a decoded character next to a literal "&", can spell a new reference that the no-encode escaper leaves alone and the browser decodes again. "&" rendered as "&" and displayed "&", and "©" displayed "(c)". Escape "&" in text that contains a numeric reference, both the decoded ones and the literal ones that do not already start a reference.
This commit is contained in:
+11
-3
@@ -32,12 +32,20 @@ export function escapeHtmlEntities(html: string, encode?: boolean) {
|
||||
* replacement character.
|
||||
*/
|
||||
export function decodeNumericCharacterReferences(text: string) {
|
||||
return text.replace(other.numericCharacterReference, (_, dec: string, hex: string) => {
|
||||
const code = dec === undefined ? Number.parseInt(hex, 16) : Number.parseInt(dec, 10);
|
||||
if (!other.numericCharacterReference.test(text)) {
|
||||
return text;
|
||||
}
|
||||
// A decoded character must not join its neighbours into a new reference,
|
||||
// so every `&` that is not already one is escaped here.
|
||||
return text.replace(other.numericCharacterReferenceOrAmpersand, (ref: string, dec?: string, hex?: string) => {
|
||||
if (dec === undefined && hex === undefined) {
|
||||
return '&';
|
||||
}
|
||||
const code = dec === undefined ? Number.parseInt(hex!, 16) : Number.parseInt(dec, 10);
|
||||
if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) {
|
||||
return '�';
|
||||
}
|
||||
return String.fromCodePoint(code);
|
||||
return code === 38 ? '&' : String.fromCodePoint(code);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -79,7 +79,8 @@ export const other = {
|
||||
endAngleBracket: />$/,
|
||||
pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/,
|
||||
unicodeAlphaNumeric: /[\p{L}\p{N}]/u,
|
||||
numericCharacterReference: /&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/g,
|
||||
numericCharacterReference: /&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,
|
||||
numericCharacterReferenceOrAmpersand: /&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
|
||||
escapeTest: /[&<>"']/,
|
||||
escapeReplace: /[&<>"']/g,
|
||||
escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,
|
||||
|
||||
@@ -3,3 +3,5 @@
|
||||
<p>�</p>
|
||||
<p>&#abcdef0;</p>
|
||||
<p><code>&#35;</code></p>
|
||||
<p>&amp; &lt;</p>
|
||||
<p>&#35; &copy; &amp;</p>
|
||||
|
||||
@@ -10,3 +10,7 @@ renderExact: true
|
||||
&#abcdef0;
|
||||
|
||||
`#`
|
||||
|
||||
&amp; &lt;
|
||||
|
||||
&#35; &copy; &;
|
||||
|
||||
Reference in New Issue
Block a user