Decode numeric HTML entities
Turn é and é style references into characters.
function decodeNumericEntities(text) { return text.replace(/&#(x[0-9a-f]+|\d+);/gi, (entity, code) => { const point = code[0].toLowerCase() === 'x' ? parseInt(code.slice(1), 16) : Number(code); return point <= 0x10ffff ? String.fromCodePoint(point) : entity; }); }
Input & expected output
Input
"Café 😀"Expected output
"Café 😀"The edge case
Input
"�"Expected output
"�"Know the limits
- Numeric references only; named ones such as é need an HTML parser. The original regex mishandled hexadecimal references.
- Out-of-range code points are left unchanged.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Decode HTML entities from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Rewritten for decimal and hexadecimal numeric references with a code-point range check; the original regex mishandled hexadecimal references. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Capitalize a string — Uppercase the first Unicode code point and preserve the remaining text.
- Reverse a string — Reverse Unicode code points without splitting surrogate pairs.
- Check a palindrome — Compare a string with its code-point reversal.