QuoteJSONString.js 1.3 KB

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