index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import {decodeNamedCharacterReference} from 'decode-named-character-reference'
  2. import {decodeNumericCharacterReference} from 'micromark-util-decode-numeric-character-reference'
  3. const characterEscapeOrReference =
  4. /\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi
  5. /**
  6. * Decode markdown strings (which occur in places such as fenced code info
  7. * strings, destinations, labels, and titles).
  8. *
  9. * The “string” content type allows character escapes and -references.
  10. * This decodes those.
  11. *
  12. * @param {string} value
  13. * Value to decode.
  14. * @returns {string}
  15. * Decoded value.
  16. */
  17. export function decodeString(value) {
  18. return value.replace(characterEscapeOrReference, decode)
  19. }
  20. /**
  21. * @param {string} $0
  22. * @param {string} $1
  23. * @param {string} $2
  24. * @returns {string}
  25. */
  26. function decode($0, $1, $2) {
  27. if ($1) {
  28. // Escape.
  29. return $1
  30. }
  31. // Reference.
  32. const head = $2.charCodeAt(0)
  33. if (head === 35) {
  34. const head = $2.charCodeAt(1)
  35. const hex = head === 120 || head === 88
  36. return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10)
  37. }
  38. return decodeNamedCharacterReference($2) || $0
  39. }