QuoteJSONString.js 1.4 KB

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