Tim van der Lippe | 2c89197 | 2021-07-29 15:22:50 | [diff] [blame] | 1 | 'use strict'; |
| 2 | |
Nikolay Vitkov | d76576c | 2024-12-02 14:10:15 | [diff] [blame] | 3 | var $TypeError = require('es-errors/type'); |
Tim van der Lippe | 2c89197 | 2021-07-29 15:22:50 | [diff] [blame] | 4 | |
| 5 | var callBound = require('call-bind/callBound'); |
| 6 | var forEach = require('../helpers/forEach'); |
| 7 | |
| 8 | var $charCodeAt = callBound('String.prototype.charCodeAt'); |
| 9 | var $numberToString = callBound('Number.prototype.toString'); |
| 10 | var $toLowerCase = callBound('String.prototype.toLowerCase'); |
| 11 | var $strSlice = callBound('String.prototype.slice'); |
| 12 | var $strSplit = callBound('String.prototype.split'); |
| 13 | |
Nikolay Vitkov | d76576c | 2024-12-02 14:10:15 | [diff] [blame] | 14 | // https://262.ecma-international.org/6.0/#sec-quotejsonstring |
Tim van der Lippe | 2c89197 | 2021-07-29 15:22:50 | [diff] [blame] | 15 | |
| 16 | var escapes = { |
| 17 | '\u0008': 'b', |
| 18 | '\u000C': 'f', |
| 19 | '\u000A': 'n', |
| 20 | '\u000D': 'r', |
| 21 | '\u0009': 't' |
| 22 | }; |
| 23 | |
| 24 | module.exports = function QuoteJSONString(value) { |
Nikolay Vitkov | d76576c | 2024-12-02 14:10:15 | [diff] [blame] | 25 | if (typeof value !== 'string') { |
Tim van der Lippe | 2c89197 | 2021-07-29 15:22:50 | [diff] [blame] | 26 | throw new $TypeError('Assertion failed: `value` must be a String'); |
| 27 | } |
| 28 | var product = '"'; |
| 29 | if (value) { |
| 30 | forEach($strSplit(value), function (C) { |
| 31 | if (C === '"' || C === '\\') { |
| 32 | product += '\u005C' + C; |
| 33 | } else if (C === '\u0008' || C === '\u000C' || C === '\u000A' || C === '\u000D' || C === '\u0009') { |
| 34 | var abbrev = escapes[C]; |
| 35 | product += '\u005C' + abbrev; |
| 36 | } else { |
| 37 | var cCharCode = $charCodeAt(C, 0); |
| 38 | if (cCharCode < 0x20) { |
| 39 | product += '\u005Cu' + $toLowerCase($strSlice('0000' + $numberToString(cCharCode, 16), -4)); |
| 40 | } else { |
| 41 | product += C; |
| 42 | } |
| 43 | } |
| 44 | }); |
| 45 | } |
| 46 | product += '"'; |
| 47 | return product; |
| 48 | }; |