index.js 661 B

1234567891011121314151617181920212223242526
  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. * @returns {string}
  19. */
  20. function replace(value) {
  21. // @ts-expect-error Hush, it’s fine.
  22. return '&' + characterReferences[value] + ';'
  23. }
  24. }