1 | # jsesc [![Build status](https://travis-ci.org/mathiasbynens/jsesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/jsesc) [![Code coverage status](https://coveralls.io/repos/mathiasbynens/jsesc/badge.svg)](https://coveralls.io/r/mathiasbynens/jsesc) [![Dependency status](https://gemnasium.com/mathiasbynens/jsesc.svg)](https://gemnasium.com/mathiasbynens/jsesc)
|
2 |
|
3 | Given some data, _jsesc_ returns a stringified representation of that data. jsesc is similar to `JSON.stringify()` except:
|
4 |
|
5 | 1. it outputs JavaScript instead of JSON [by default](#json), enabling support for data structures like ES6 maps and sets;
|
6 | 2. it offers [many options](#api) to customize the output;
|
7 | 3. its output is ASCII-safe [by default](#minimal), thanks to its use of [escape sequences](https://mathiasbynens.be/notes/javascript-escapes) where needed.
|
8 |
|
9 | For any input, jsesc generates the shortest possible valid printable-ASCII-only output. [Here’s an online demo.](https://mothereff.in/js-escapes)
|
10 |
|
11 | jsesc’s output can be used instead of `JSON.stringify`’s to avoid [mojibake](https://en.wikipedia.org/wiki/Mojibake) and other encoding issues, or even to [avoid errors](https://twitter.com/annevk/status/380000829643571200) when passing JSON-formatted data (which may contain U+2028 LINE SEPARATOR, U+2029 PARAGRAPH SEPARATOR, or [lone surrogates](https://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)) to a JavaScript parser or an UTF-8 encoder.
|
12 |
|
13 | ## Installation
|
14 |
|
15 | Via [npm](https://www.npmjs.com/):
|
16 |
|
17 | ```bash
|
18 | npm install jsesc
|
19 | ```
|
20 |
|
21 | In [Node.js](https://nodejs.org/):
|
22 |
|
23 | ```js
|
24 | const jsesc = require('jsesc');
|
25 | ```
|
26 |
|
27 | ## API
|
28 |
|
29 | ### `jsesc(value, options)`
|
30 |
|
31 | This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in JavaScript strings](https://mathiasbynens.be/notes/javascript-escapes). The first supported value type is strings:
|
32 |
|
33 | ```js
|
34 | jsesc('Ich ♥ Bücher');
|
35 | // → 'Ich \\u2665 B\\xFCcher'
|
36 |
|
37 | jsesc('foo 𝌆 bar');
|
38 | // → 'foo \\uD834\\uDF06 bar'
|
39 | ```
|
40 |
|
41 | Instead of a string, the `value` can also be an array, an object, a map, a set, or a buffer. In such cases, `jsesc` returns a stringified version of the value where any characters that are not printable ASCII symbols are escaped in the same way.
|
42 |
|
43 | ```js
|
44 | // Escaping an array
|
45 | jsesc([
|
46 | 'Ich ♥ Bücher', 'foo 𝌆 bar'
|
47 | ]);
|
48 | // → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']'
|
49 |
|
50 | // Escaping an object
|
51 | jsesc({
|
52 | 'Ich ♥ Bücher': 'foo 𝌆 bar'
|
53 | });
|
54 | // → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}'
|
55 | ```
|
56 |
|
57 | The optional `options` argument accepts an object with the following options:
|
58 |
|
59 | #### `quotes`
|
60 |
|
61 | The default value for the `quotes` option is `'single'`. This means that any occurrences of `'` in the input string are escaped as `\'`, so that the output can be used in a string literal wrapped in single quotes.
|
62 |
|
63 | ```js
|
64 | jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.');
|
65 | // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
|
66 |
|
67 | jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
|
68 | 'quotes': 'single'
|
69 | });
|
70 | // → '`Lorem` ipsum "dolor" sit \\\'amet\\\' etc.'
|
71 | // → "`Lorem` ipsum \"dolor\" sit \\'amet\\' etc."
|
72 | ```
|
73 |
|
74 | If you want to use the output as part of a string literal wrapped in double quotes, set the `quotes` option to `'double'`.
|
75 |
|
76 | ```js
|
77 | jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
|
78 | 'quotes': 'double'
|
79 | });
|
80 | // → '`Lorem` ipsum \\"dolor\\" sit \'amet\' etc.'
|
81 | // → "`Lorem` ipsum \\\"dolor\\\" sit 'amet' etc."
|
82 | ```
|
83 |
|
84 | If you want to use the output as part of a template literal (i.e. wrapped in backticks), set the `quotes` option to `'backtick'`.
|
85 |
|
86 | ```js
|
87 | jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
|
88 | 'quotes': 'backtick'
|
89 | });
|
90 | // → '\\`Lorem\\` ipsum "dolor" sit \'amet\' etc.'
|
91 | // → "\\`Lorem\\` ipsum \"dolor\" sit 'amet' etc."
|
92 | // → `\\\`Lorem\\\` ipsum "dolor" sit 'amet' etc.`
|
93 | ```
|
94 |
|
95 | This setting also affects the output for arrays and objects:
|
96 |
|
97 | ```js
|
98 | jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
|
99 | 'quotes': 'double'
|
100 | });
|
101 | // → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}'
|
102 |
|
103 | jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
|
104 | 'quotes': 'double'
|
105 | });
|
106 | // → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]'
|
107 | ```
|
108 |
|
109 | #### `numbers`
|
110 |
|
111 | The default value for the `numbers` option is `'decimal'`. This means that any numeric values are represented using decimal integer literals. Other valid options are `binary`, `octal`, and `hexadecimal`, which result in binary integer literals, octal integer literals, and hexadecimal integer literals, respectively.
|
112 |
|
113 | ```js
|
114 | jsesc(42, {
|
115 | 'numbers': 'binary'
|
116 | });
|
117 | // → '0b101010'
|
118 |
|
119 | jsesc(42, {
|
120 | 'numbers': 'octal'
|
121 | });
|
122 | // → '0o52'
|
123 |
|
124 | jsesc(42, {
|
125 | 'numbers': 'decimal'
|
126 | });
|
127 | // → '42'
|
128 |
|
129 | jsesc(42, {
|
130 | 'numbers': 'hexadecimal'
|
131 | });
|
132 | // → '0x2A'
|
133 | ```
|
134 |
|
135 | #### `wrap`
|
136 |
|
137 | The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is a valid JavaScript string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting.
|
138 |
|
139 | ```js
|
140 | jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
|
141 | 'quotes': 'single',
|
142 | 'wrap': true
|
143 | });
|
144 | // → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\''
|
145 | // → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'"
|
146 |
|
147 | jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
|
148 | 'quotes': 'double',
|
149 | 'wrap': true
|
150 | });
|
151 | // → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."'
|
152 | // → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\""
|
153 | ```
|
154 |
|
155 | #### `es6`
|
156 |
|
157 | The `es6` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any astral Unicode symbols in the input are escaped using [ECMAScript 6 Unicode code point escape sequences](https://mathiasbynens.be/notes/javascript-escapes#unicode-code-point) instead of using separate escape sequences for each surrogate half. If backwards compatibility with ES5 environments is a concern, don’t enable this setting. If the `json` setting is enabled, the value for the `es6` setting is ignored (as if it was `false`).
|
158 |
|
159 | ```js
|
160 | // By default, the `es6` option is disabled:
|
161 | jsesc('foo 𝌆 bar 💩 baz');
|
162 | // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'
|
163 |
|
164 | // To explicitly disable it:
|
165 | jsesc('foo 𝌆 bar 💩 baz', {
|
166 | 'es6': false
|
167 | });
|
168 | // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'
|
169 |
|
170 | // To enable it:
|
171 | jsesc('foo 𝌆 bar 💩 baz', {
|
172 | 'es6': true
|
173 | });
|
174 | // → 'foo \\u{1D306} bar \\u{1F4A9} baz'
|
175 | ```
|
176 |
|
177 | #### `escapeEverything`
|
178 |
|
179 | The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output are escaped — even printable ASCII symbols.
|
180 |
|
181 | ```js
|
182 | jsesc('lolwat"foo\'bar', {
|
183 | 'escapeEverything': true
|
184 | });
|
185 | // → '\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72'
|
186 | // → "\\x6C\\x6F\\x6C\\x77\\x61\\x74\\\"\\x66\\x6F\\x6F\\'\\x62\\x61\\x72"
|
187 | ```
|
188 |
|
189 | This setting also affects the output for string literals within arrays and objects.
|
190 |
|
191 | #### `minimal`
|
192 |
|
193 | The `minimal` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, only a limited set of symbols in the output are escaped:
|
194 |
|
195 | * U+0000 `\0`
|
196 | * U+0008 `\b`
|
197 | * U+0009 `\t`
|
198 | * U+000A `\n`
|
199 | * U+000C `\f`
|
200 | * U+000D `\r`
|
201 | * U+005C `\\`
|
202 | * U+2028 `\u2028`
|
203 | * U+2029 `\u2029`
|
204 | * whatever symbol is being used for wrapping string literals (based on [the `quotes` option](#quotes))
|
205 |
|
206 | Note: with this option enabled, jsesc output is no longer guaranteed to be ASCII-safe.
|
207 |
|
208 | ```js
|
209 | jsesc('foo\u2029bar\nbaz©qux𝌆flops', {
|
210 | 'minimal': false
|
211 | });
|
212 | // → 'foo\\u2029bar\\nbaz©qux𝌆flops'
|
213 | ```
|
214 |
|
215 | #### `isScriptContext`
|
216 |
|
217 | The `isScriptContext` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, occurrences of [`</script` and `</style`](https://mathiasbynens.be/notes/etago) in the output are escaped as `<\/script` and `<\/style`, and [`<!--`](https://mathiasbynens.be/notes/etago#comment-8) is escaped as `\x3C!--` (or `\u003C!--` when the `json` option is enabled). This setting is useful when jsesc’s output ends up as part of a `<script>` or `<style>` element in an HTML document.
|
218 |
|
219 | ```js
|
220 | jsesc('foo</script>bar', {
|
221 | 'isScriptContext': true
|
222 | });
|
223 | // → 'foo<\\/script>bar'
|
224 | ```
|
225 |
|
226 | #### `compact`
|
227 |
|
228 | The `compact` option takes a boolean value (`true` or `false`), and defaults to `true` (enabled). When enabled, the output for arrays and objects is as compact as possible; it’s not formatted nicely.
|
229 |
|
230 | ```js
|
231 | jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
|
232 | 'compact': true // this is the default
|
233 | });
|
234 | // → '{\'Ich \u2665 B\xFCcher\':\'foo \uD834\uDF06 bar\'}'
|
235 |
|
236 | jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
|
237 | 'compact': false
|
238 | });
|
239 | // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
|
240 |
|
241 | jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
|
242 | 'compact': false
|
243 | });
|
244 | // → '[\n\t\'Ich \u2665 B\xFCcher\',\n\t\'foo \uD834\uDF06 bar\'\n]'
|
245 | ```
|
246 |
|
247 | This setting has no effect on the output for strings.
|
248 |
|
249 | #### `indent`
|
250 |
|
251 | The `indent` option takes a string value, and defaults to `'\t'`. When the `compact` setting is enabled (`true`), the value of the `indent` option is used to format the output for arrays and objects.
|
252 |
|
253 | ```js
|
254 | jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
|
255 | 'compact': false,
|
256 | 'indent': '\t' // this is the default
|
257 | });
|
258 | // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
|
259 |
|
260 | jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
|
261 | 'compact': false,
|
262 | 'indent': ' '
|
263 | });
|
264 | // → '{\n \'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
|
265 |
|
266 | jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
|
267 | 'compact': false,
|
268 | 'indent': ' '
|
269 | });
|
270 | // → '[\n \'Ich \u2665 B\xFCcher\',\n\ t\'foo \uD834\uDF06 bar\'\n]'
|
271 | ```
|
272 |
|
273 | This setting has no effect on the output for strings.
|
274 |
|
275 | #### `indentLevel`
|
276 |
|
277 | The `indentLevel` option takes a numeric value, and defaults to `0`. It represents the current indentation level, i.e. the number of times the value of [the `indent` option](#indent) is repeated.
|
278 |
|
279 | ```js
|
280 | jsesc(['a', 'b', 'c'], {
|
281 | 'compact': false,
|
282 | 'indentLevel': 1
|
283 | });
|
284 | // → '[\n\t\t\'a\',\n\t\t\'b\',\n\t\t\'c\'\n\t]'
|
285 |
|
286 | jsesc(['a', 'b', 'c'], {
|
287 | 'compact': false,
|
288 | 'indentLevel': 2
|
289 | });
|
290 | // → '[\n\t\t\t\'a\',\n\t\t\t\'b\',\n\t\t\t\'c\'\n\t\t]'
|
291 | ```
|
292 |
|
293 | #### `json`
|
294 |
|
295 | The `json` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is valid JSON. [Hexadecimal character escape sequences](https://mathiasbynens.be/notes/javascript-escapes#hexadecimal) and [the `\v` or `\0` escape sequences](https://mathiasbynens.be/notes/javascript-escapes#single) are not used. Setting `json: true` implies `quotes: 'double', wrap: true, es6: false`, although these values can still be overridden if needed — but in such cases, the output won’t be valid JSON anymore.
|
296 |
|
297 | ```js
|
298 | jsesc('foo\x00bar\xFF\uFFFDbaz', {
|
299 | 'json': true
|
300 | });
|
301 | // → '"foo\\u0000bar\\u00FF\\uFFFDbaz"'
|
302 |
|
303 | jsesc({ 'foo\x00bar\xFF\uFFFDbaz': 'foo\x00bar\xFF\uFFFDbaz' }, {
|
304 | 'json': true
|
305 | });
|
306 | // → '{"foo\\u0000bar\\u00FF\\uFFFDbaz":"foo\\u0000bar\\u00FF\\uFFFDbaz"}'
|
307 |
|
308 | jsesc([ 'foo\x00bar\xFF\uFFFDbaz', 'foo\x00bar\xFF\uFFFDbaz' ], {
|
309 | 'json': true
|
310 | });
|
311 | // → '["foo\\u0000bar\\u00FF\\uFFFDbaz","foo\\u0000bar\\u00FF\\uFFFDbaz"]'
|
312 |
|
313 | // Values that are acceptable in JSON but aren’t strings, arrays, or object
|
314 | // literals can’t be escaped, so they’ll just be preserved:
|
315 | jsesc([ 'foo\x00bar', [1, '©', { 'foo': true, 'qux': null }], 42 ], {
|
316 | 'json': true
|
317 | });
|
318 | // → '["foo\\u0000bar",[1,"\\u00A9",{"foo":true,"qux":null}],42]'
|
319 | // Values that aren’t allowed in JSON are run through `JSON.stringify()`:
|
320 | jsesc([ undefined, -Infinity ], {
|
321 | 'json': true
|
322 | });
|
323 | // → '[null,null]'
|
324 | ```
|
325 |
|
326 | **Note:** Using this option on objects or arrays that contain non-string values relies on `JSON.stringify()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](http://bestiejs.github.io/json3/).
|
327 |
|
328 | #### `lowercaseHex`
|
329 |
|
330 | The `lowercaseHex` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any alphabetical hexadecimal digits in escape sequences as well as any hexadecimal integer literals (see [the `numbers` option](#numbers)) in the output are in lowercase.
|
331 |
|
332 | ```js
|
333 | jsesc('Ich ♥ Bücher', {
|
334 | 'lowercaseHex': true
|
335 | });
|
336 | // → 'Ich \\u2665 B\\xfccher'
|
337 | // ^^
|
338 |
|
339 | jsesc(42, {
|
340 | 'numbers': 'hexadecimal',
|
341 | 'lowercaseHex': true
|
342 | });
|
343 | // → '0x2a'
|
344 | // ^^
|
345 | ```
|
346 |
|
347 | ### `jsesc.version`
|
348 |
|
349 | A string representing the semantic version number.
|
350 |
|
351 | ### Using the `jsesc` binary
|
352 |
|
353 | To use the `jsesc` binary in your shell, simply install jsesc globally using npm:
|
354 |
|
355 | ```bash
|
356 | npm install -g jsesc
|
357 | ```
|
358 |
|
359 | After that you’re able to escape strings from the command line:
|
360 |
|
361 | ```bash
|
362 | $ jsesc 'föo ♥ bår 𝌆 baz'
|
363 | f\xF6o \u2665 b\xE5r \uD834\uDF06 baz
|
364 | ```
|
365 |
|
366 | To escape arrays or objects containing string values, use the `-o`/`--object` option:
|
367 |
|
368 | ```bash
|
369 | $ jsesc --object '{ "föo": "♥", "bår": "𝌆 baz" }'
|
370 | {'f\xF6o':'\u2665','b\xE5r':'\uD834\uDF06 baz'}
|
371 | ```
|
372 |
|
373 | To prettify the output in such cases, use the `-p`/`--pretty` option:
|
374 |
|
375 | ```bash
|
376 | $ jsesc --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
|
377 | {
|
378 | 'f\xF6o': '\u2665',
|
379 | 'b\xE5r': '\uD834\uDF06 baz'
|
380 | }
|
381 | ```
|
382 |
|
383 | For valid JSON output, use the `-j`/`--json` option:
|
384 |
|
385 | ```bash
|
386 | $ jsesc --json --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
|
387 | {
|
388 | "f\u00F6o": "\u2665",
|
389 | "b\u00E5r": "\uD834\uDF06 baz"
|
390 | }
|
391 | ```
|
392 |
|
393 | Read a local JSON file, escape any non-ASCII symbols, and save the result to a new file:
|
394 |
|
395 | ```bash
|
396 | $ jsesc --json --object < data-raw.json > data-escaped.json
|
397 | ```
|
398 |
|
399 | Or do the same with an online JSON file:
|
400 |
|
401 | ```bash
|
402 | $ curl -sL "http://git.io/aorKgQ" | jsesc --json --object > data-escaped.json
|
403 | ```
|
404 |
|
405 | See `jsesc --help` for the full list of options.
|
406 |
|
407 | ## Support
|
408 |
|
409 | As of v2.0.0, jsesc supports Node.js v4+ only.
|
410 |
|
411 | Older versions (up to jsesc v1.3.0) support Chrome 27, Firefox 3, Safari 4, Opera 10, IE 6, Node.js v6.0.0, Narwhal 0.3.2, RingoJS 0.8-0.11, PhantomJS 1.9.0, and Rhino 1.7RC4. **Note:** Using the `json` option on objects or arrays that contain non-string values relies on `JSON.parse()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](https://bestiejs.github.io/json3/).
|
412 |
|
413 | ## Author
|
414 |
|
415 | | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|
416 | |---|
|
417 | | [Mathias Bynens](https://mathiasbynens.be/) |
|
418 |
|
419 | ## License
|
420 |
|
421 | This library is available under the [MIT](https://mths.be/mit) license.
|