index.dom.js 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. /// <reference lib="dom" />
  2. /* eslint-env browser */
  3. const element = document.createElement('i')
  4. /**
  5. * @param {string} value
  6. * @returns {string|false}
  7. */
  8. export function decodeNamedCharacterReference(value) {
  9. const characterReference = '&' + value + ';'
  10. element.innerHTML = characterReference
  11. const char = element.textContent
  12. // Some named character references do not require the closing semicolon
  13. // (`&not`, for instance), which leads to situations where parsing the assumed
  14. // named reference of `&notit;` will result in the string `¬it;`.
  15. // When we encounter a trailing semicolon after parsing, and the character
  16. // reference to decode was not a semicolon (`&semi;`), we can assume that the
  17. // matching was not complete.
  18. // @ts-expect-error: TypeScript is wrong that `textContent` on elements can
  19. // yield `null`.
  20. if (char.charCodeAt(char.length - 1) === 59 /* `;` */ && value !== 'semi') {
  21. return false
  22. }
  23. // If the decoded string is equal to the input, the character reference was
  24. // not valid.
  25. // @ts-expect-error: TypeScript is wrong that `textContent` on elements can
  26. // yield `null`.
  27. return char === characterReference ? false : char
  28. }