to-named.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import {characterEntitiesLegacy} from 'character-entities-legacy'
  2. import {characterEntitiesHtml4} from 'character-entities-html4'
  3. import {dangerous} from '../constant/dangerous.js'
  4. const own = {}.hasOwnProperty
  5. /**
  6. * `characterEntitiesHtml4` but inverted.
  7. *
  8. * @type {Record<string, string>}
  9. */
  10. const characters = {}
  11. /** @type {string} */
  12. let key
  13. for (key in characterEntitiesHtml4) {
  14. if (own.call(characterEntitiesHtml4, key)) {
  15. characters[characterEntitiesHtml4[key]] = key
  16. }
  17. }
  18. const notAlphanumericRegex = /[^\dA-Za-z]/
  19. /**
  20. * Configurable ways to encode characters as named references.
  21. *
  22. * @param {number} code
  23. * @param {number} next
  24. * @param {boolean|undefined} omit
  25. * @param {boolean|undefined} attribute
  26. * @returns {string}
  27. */
  28. export function toNamed(code, next, omit, attribute) {
  29. const character = String.fromCharCode(code)
  30. if (own.call(characters, character)) {
  31. const name = characters[character]
  32. const value = '&' + name
  33. if (
  34. omit &&
  35. characterEntitiesLegacy.includes(name) &&
  36. !dangerous.includes(name) &&
  37. (!attribute ||
  38. (next &&
  39. next !== 61 /* `=` */ &&
  40. notAlphanumericRegex.test(String.fromCharCode(next))))
  41. ) {
  42. return value
  43. }
  44. return value + ';'
  45. }
  46. return ''
  47. }