QuoteJSONString.js 1.4 KB

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