Created
January 9, 2024 15:48
-
-
Save Jpoliachik/7f6d93b581175c693518db60a9851cfa to your computer and use it in GitHub Desktop.
decodeHtml.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const entities = { | |
amp: "&", | |
apos: "'", | |
lt: "<", | |
gt: ">", | |
quot: '"', | |
nbsp: "\xa0", | |
ouml: "ö", | |
auml: "ä", | |
uuml: "ü", | |
oacute: "ó", | |
aacute: "á", | |
eacute: "é", | |
ntilde: "ñ", | |
"#039": "'", | |
} | |
const entityPattern = /&(([a-z0-9]|#)+);/gi | |
export const decodeHTMLEntities = (text: string): string => { | |
// A single replace pass with a static RegExp is faster than a loop | |
return text.replace(entityPattern, (match, entity) => { | |
entity = entity.toLowerCase() | |
if (Object.prototype.hasOwnProperty.call(entities, entity)) { | |
return entities[entity as keyof typeof entities] | |
} | |
// return original string if there is no matching entity (no replace) | |
return match | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment