index.js 757 B

123456789101112131415161718192021222324252627282930313233
  1. const characterReferences = {'"': 'quot', '&': 'amp', '<': 'lt', '>': 'gt'}
  2. /**
  3. * Encode only the dangerous HTML characters.
  4. *
  5. * This ensures that certain characters which have special meaning in HTML are
  6. * dealt with.
  7. * Technically, we can skip `>` and `"` in many cases, but CM includes them.
  8. *
  9. * @param {string} value
  10. * Value to encode.
  11. * @returns {string}
  12. * Encoded value.
  13. */
  14. export function encode(value) {
  15. return value.replace(/["&<>]/g, replace)
  16. /**
  17. * @param {string} value
  18. * Value to replace.
  19. * @returns {string}
  20. * Encoded value.
  21. */
  22. function replace(value) {
  23. return (
  24. '&' +
  25. characterReferences[
  26. /** @type {keyof typeof characterReferences} */ (value)
  27. ] +
  28. ';'
  29. )
  30. }
  31. }