QuoteJSONString.js 1007 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 $charCodeAt = callBound('String.prototype.charCodeAt');
  6. var $strSplit = callBound('String.prototype.split');
  7. var UnicodeEscape = require('./UnicodeEscape');
  8. var hasOwn = require('hasown');
  9. // https://262.ecma-international.org/9.0/#sec-quotejsonstring
  10. var escapes = {
  11. '\u0008': '\\b',
  12. '\u0009': '\\t',
  13. '\u000A': '\\n',
  14. '\u000C': '\\f',
  15. '\u000D': '\\r',
  16. '\u0022': '\\"',
  17. '\u005c': '\\\\'
  18. };
  19. module.exports = function QuoteJSONString(value) {
  20. if (typeof value !== 'string') {
  21. throw new $TypeError('Assertion failed: `value` must be a String');
  22. }
  23. var product = '"';
  24. if (value) {
  25. forEach($strSplit(value), function (C) {
  26. if (hasOwn(escapes, C)) {
  27. product += escapes[C];
  28. } else if ($charCodeAt(C, 0) < 0x20) {
  29. product += UnicodeEscape(C);
  30. } else {
  31. product += C;
  32. }
  33. });
  34. }
  35. product += '"';
  36. return product;
  37. };