Sanitize.mjs 667 B

12345678910111213141516171819202122
  1. // @ts-check
  2. /* eslint-disable no-control-regex, no-misleading-character-class */
  3. const CONTROL_CHARS_RE =
  4. /[\u0000-\u001F\u007F-\u009F\u200B\u200C\u200D\u2060\uFEFF]/g
  5. /* eslint-enable no-control-regex, no-misleading-character-class */
  6. /**
  7. * @param {string} value
  8. * @returns {string}
  9. */
  10. export function sanitizeControlCharacters(value) {
  11. if (typeof value !== 'string') {
  12. throw new TypeError(
  13. `sanitizeControlCharacters expected a string, received ${typeof value}`
  14. )
  15. }
  16. return value.replace(CONTROL_CHARS_RE, char => {
  17. const code = /** @type {number} */ (char.codePointAt(0))
  18. return `\\u${code.toString(16).padStart(4, '0')}`
  19. })
  20. }