fix: decode numeric character references in text (#4076)

This commit is contained in:
Miodrag Obradovic
2026-09-20 20:50:50 -06:00
committed by GitHub
parent e136da7c7d
commit cead8de96f
5 changed files with 37 additions and 1 deletions
+4 -1
View File
@@ -5,6 +5,7 @@ import {
findClosingBracket,
expandTabs,
normalizeLabel,
decodeNumericCharacterReferences,
trimTrailingBlankLines,
} from './helpers.ts';
import type { Rules } from './rules.ts';
@@ -1046,7 +1047,9 @@ export class _Tokenizer<ParserOutput = string, RendererOutput = string> {
return {
type: 'text',
raw: cap[0],
text: cap[0],
// raw HTML keeps whatever it was written with, everywhere else a numeric
// character reference stands for the character itself
text: escaped ? cap[0] : decodeNumericCharacterReferences(cap[0]),
escaped,
};
}
+15
View File
@@ -26,6 +26,21 @@ export function escapeHtmlEntities(html: string, encode?: boolean) {
return html;
}
/**
* Numeric character references are recognized outside code and are equivalent to the
* character they name. Values that are zero, out of range, or a surrogate become the
* 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 (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) {
return '�';
}
return String.fromCodePoint(code);
});
}
export function cleanUrl(href: string) {
try {
href = encodeURI(href).replace(other.percentDecode, '%');
+1
View File
@@ -79,6 +79,7 @@ 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,
escapeTest: /[&<>"']/,
escapeReplace: /[&<>"']/g,
escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,
@@ -0,0 +1,5 @@
<p># Ӓ</p>
<p>&quot; ಫ</p>
<p>�</p>
<p>&amp;#abcdef0;</p>
<p><code>&amp;#35;</code></p>
@@ -0,0 +1,12 @@
---
renderExact: true
---
&#35; &#1234;
&#X22; &#xcab;
&#0;
&#abcdef0;
`&#35;`