QuoteJSONString.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var callBound = require('call-bound');
  4. var forEach = require('../helpers/forEach');
  5. var isLeadingSurrogate = require('../helpers/isLeadingSurrogate');
  6. var isTrailingSurrogate = require('../helpers/isTrailingSurrogate');
  7. var $charCodeAt = callBound('String.prototype.charCodeAt');
  8. var $strSplit = callBound('String.prototype.split');
  9. var UnicodeEscape = require('./UnicodeEscape');
  10. var UTF16DecodeString = require('./UTF16DecodeString');
  11. var UTF16Encoding = require('./UTF16Encoding');
  12. var hasOwn = require('hasown');
  13. // https://262.ecma-international.org/11.0/#sec-quotejsonstring
  14. var escapes = {
  15. '\u0008': '\\b',
  16. '\u0009': '\\t',
  17. '\u000A': '\\n',
  18. '\u000C': '\\f',
  19. '\u000D': '\\r',
  20. '\u0022': '\\"',
  21. '\u005c': '\\\\'
  22. };
  23. module.exports = function QuoteJSONString(value) {
  24. if (typeof value !== 'string') {
  25. throw new $TypeError('Assertion failed: `value` must be a String');
  26. }
  27. var product = '"';
  28. if (value) {
  29. forEach($strSplit(UTF16DecodeString(value), ''), function (C) {
  30. if (hasOwn(escapes, C)) {
  31. product += escapes[C];
  32. } else {
  33. var cCharCode = $charCodeAt(C, 0);
  34. if (cCharCode < 0x20 || isLeadingSurrogate(cCharCode) || isTrailingSurrogate(cCharCode)) {
  35. product += UnicodeEscape(C);
  36. } else {
  37. product += UTF16Encoding(cCharCode);
  38. }
  39. }
  40. });
  41. }
  42. product += '"';
  43. return product;
  44. };