quote.ts 740 B

1234567891011121314151617181920212223242526272829
  1. // eslint-disable-next-line no-control-regex, no-misleading-character-class
  2. const rxEscapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g
  3. const escaped: {[K in string]?: string} = {
  4. "\b": "\\b",
  5. "\t": "\\t",
  6. "\n": "\\n",
  7. "\f": "\\f",
  8. "\r": "\\r",
  9. '"': '\\"',
  10. "\\": "\\\\",
  11. }
  12. export default function quote(s: string): string {
  13. rxEscapable.lastIndex = 0
  14. return (
  15. '"' +
  16. (rxEscapable.test(s)
  17. ? s.replace(rxEscapable, (a) => {
  18. const c = escaped[a]
  19. return typeof c === "string"
  20. ? c
  21. : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
  22. })
  23. : s) +
  24. '"'
  25. )
  26. }