QuoteJSONString.js 1.0 KB

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