Skip to content

Instantly share code, notes, and snippets.

@Jpoliachik
Created January 9, 2024 15:48
Show Gist options
  • Save Jpoliachik/7f6d93b581175c693518db60a9851cfa to your computer and use it in GitHub Desktop.
Save Jpoliachik/7f6d93b581175c693518db60a9851cfa to your computer and use it in GitHub Desktop.
decodeHtml.ts
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