QuoteJSONString.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 $numberToString = callBound('Number.prototype.toString');
  7. var $toLowerCase = callBound('String.prototype.toLowerCase');
  8. var $strSlice = callBound('String.prototype.slice');
  9. var $strSplit = callBound('String.prototype.split');
  10. // https://262.ecma-international.org/6.0/#sec-quotejsonstring
  11. var escapes = {
  12. '\u0008': 'b',
  13. '\u000C': 'f',
  14. '\u000A': 'n',
  15. '\u000D': 'r',
  16. '\u0009': 't'
  17. };
  18. module.exports = function QuoteJSONString(value) {
  19. if (typeof value !== 'string') {
  20. throw new $TypeError('Assertion failed: `value` must be a String');
  21. }
  22. var product = '"';
  23. if (value) {
  24. forEach($strSplit(value), function (C) {
  25. if (C === '"' || C === '\\') {
  26. product += '\u005C' + C;
  27. } else if (C === '\u0008' || C === '\u000C' || C === '\u000A' || C === '\u000D' || C === '\u0009') {
  28. var abbrev = escapes[C];
  29. product += '\u005C' + abbrev;
  30. } else {
  31. var cCharCode = $charCodeAt(C, 0);
  32. if (cCharCode < 0x20) {
  33. product += '\u005Cu' + $toLowerCase($strSlice('0000' + $numberToString(cCharCode, 16), -4));
  34. } else {
  35. product += C;
  36. }
  37. }
  38. });
  39. }
  40. product += '"';
  41. return product;
  42. };