UNPKG

14.5 kBMarkdownView Raw
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)
2
3Given some data, _jsesc_ returns a stringified representation of that data. jsesc is similar to `JSON.stringify()` except:
4
51. it outputs JavaScript instead of JSON [by default](#json), enabling support for data structures like ES6 maps and sets;
62. it offers [many options](#api) to customize the output;
73. its output is ASCII-safe [by default](#minimal), thanks to its use of [escape sequences](https://mathiasbynens.be/notes/javascript-escapes) where needed.
8
9For any input, jsesc generates the shortest possible valid printable-ASCII-only output. [Here’s an online demo.](https://mothereff.in/js-escapes)
10
11jsesc’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
15Via [npm](https://www.npmjs.com/):
16
17```bash
18npm install jsesc
19```
20
21In [Node.js](https://nodejs.org/):
22
23```js
24const jsesc = require('jsesc');
25```
26
27## API
28
29### `jsesc(value, options)`
30
31This 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
34jsesc('Ich ♥ Bücher');
35// → 'Ich \\u2665 B\\xFCcher'
36
37jsesc('foo 𝌆 bar');
38// → 'foo \\uD834\\uDF06 bar'
39```
40
41Instead 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
45jsesc([
46 'Ich ♥ Bücher', 'foo 𝌆 bar'
47]);
48// → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']'
49
50// Escaping an object
51jsesc({
52 'Ich ♥ Bücher': 'foo 𝌆 bar'
53});
54// → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}'
55```
56
57The optional `options` argument accepts an object with the following options:
58
59#### `quotes`
60
61The 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
64jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.');
65// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
66
67jsesc('`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
74If 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
77jsesc('`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
84If 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
87jsesc('`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
95This setting also affects the output for arrays and objects:
96
97```js
98jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
99 'quotes': 'double'
100});
101// → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}'
102
103jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
104 'quotes': 'double'
105});
106// → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]'
107```
108
109#### `numbers`
110
111The 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
114jsesc(42, {
115 'numbers': 'binary'
116});
117// → '0b101010'
118
119jsesc(42, {
120 'numbers': 'octal'
121});
122// → '0o52'
123
124jsesc(42, {
125 'numbers': 'decimal'
126});
127// → '42'
128
129jsesc(42, {
130 'numbers': 'hexadecimal'
131});
132// → '0x2A'
133```
134
135#### `wrap`
136
137The `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
140jsesc('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
147jsesc('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
157The `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:
161jsesc('foo 𝌆 bar 💩 baz');
162// → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'
163
164// To explicitly disable it:
165jsesc('foo 𝌆 bar 💩 baz', {
166 'es6': false
167});
168// → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'
169
170// To enable it:
171jsesc('foo 𝌆 bar 💩 baz', {
172 'es6': true
173});
174// → 'foo \\u{1D306} bar \\u{1F4A9} baz'
175```
176
177#### `escapeEverything`
178
179The `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
182jsesc('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
189This setting also affects the output for string literals within arrays and objects.
190
191#### `minimal`
192
193The `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* [lone surrogates](https://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)
206
207Note: with this option enabled, jsesc output is no longer guaranteed to be ASCII-safe.
208
209```js
210jsesc('foo\u2029bar\nbaz©qux𝌆flops', {
211 'minimal': false
212});
213// → 'foo\\u2029bar\\nbaz©qux𝌆flops'
214```
215
216#### `isScriptContext`
217
218The `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.
219
220```js
221jsesc('foo</script>bar', {
222 'isScriptContext': true
223});
224// → 'foo<\\/script>bar'
225```
226
227#### `compact`
228
229The `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.
230
231```js
232jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
233 'compact': true // this is the default
234});
235// → '{\'Ich \u2665 B\xFCcher\':\'foo \uD834\uDF06 bar\'}'
236
237jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
238 'compact': false
239});
240// → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
241
242jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
243 'compact': false
244});
245// → '[\n\t\'Ich \u2665 B\xFCcher\',\n\t\'foo \uD834\uDF06 bar\'\n]'
246```
247
248This setting has no effect on the output for strings.
249
250#### `indent`
251
252The `indent` option takes a string value, and defaults to `'\t'`. When the `compact` setting is disabled (`false`), the value of the `indent` option is used to format the output for arrays and objects.
253
254```js
255jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
256 'compact': false,
257 'indent': '\t' // this is the default
258});
259// → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
260
261jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
262 'compact': false,
263 'indent': ' '
264});
265// → '{\n \'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
266
267jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
268 'compact': false,
269 'indent': ' '
270});
271// → '[\n \'Ich \u2665 B\xFCcher\',\n\ t\'foo \uD834\uDF06 bar\'\n]'
272```
273
274This setting has no effect on the output for strings.
275
276#### `indentLevel`
277
278The `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.
279
280```js
281jsesc(['a', 'b', 'c'], {
282 'compact': false,
283 'indentLevel': 1
284});
285// → '[\n\t\t\'a\',\n\t\t\'b\',\n\t\t\'c\'\n\t]'
286
287jsesc(['a', 'b', 'c'], {
288 'compact': false,
289 'indentLevel': 2
290});
291// → '[\n\t\t\t\'a\',\n\t\t\t\'b\',\n\t\t\t\'c\'\n\t\t]'
292```
293
294#### `json`
295
296The `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.
297
298```js
299jsesc('foo\x00bar\xFF\uFFFDbaz', {
300 'json': true
301});
302// → '"foo\\u0000bar\\u00FF\\uFFFDbaz"'
303
304jsesc({ 'foo\x00bar\xFF\uFFFDbaz': 'foo\x00bar\xFF\uFFFDbaz' }, {
305 'json': true
306});
307// → '{"foo\\u0000bar\\u00FF\\uFFFDbaz":"foo\\u0000bar\\u00FF\\uFFFDbaz"}'
308
309jsesc([ 'foo\x00bar\xFF\uFFFDbaz', 'foo\x00bar\xFF\uFFFDbaz' ], {
310 'json': true
311});
312// → '["foo\\u0000bar\\u00FF\\uFFFDbaz","foo\\u0000bar\\u00FF\\uFFFDbaz"]'
313
314// Values that are acceptable in JSON but aren’t strings, arrays, or object
315// literals can’t be escaped, so they’ll just be preserved:
316jsesc([ 'foo\x00bar', [1, '©', { 'foo': true, 'qux': null }], 42 ], {
317 'json': true
318});
319// → '["foo\\u0000bar",[1,"\\u00A9",{"foo":true,"qux":null}],42]'
320// Values that aren’t allowed in JSON are run through `JSON.stringify()`:
321jsesc([ undefined, -Infinity ], {
322 'json': true
323});
324// → '[null,null]'
325```
326
327**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/).
328
329#### `lowercaseHex`
330
331The `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.
332
333```js
334jsesc('Ich ♥ Bücher', {
335 'lowercaseHex': true
336});
337// → 'Ich \\u2665 B\\xfccher'
338// ^^
339
340jsesc(42, {
341 'numbers': 'hexadecimal',
342 'lowercaseHex': true
343});
344// → '0x2a'
345// ^^
346```
347
348### `jsesc.version`
349
350A string representing the semantic version number.
351
352### Using the `jsesc` binary
353
354To use the `jsesc` binary in your shell, simply install jsesc globally using npm:
355
356```bash
357npm install -g jsesc
358```
359
360After that you’re able to escape strings from the command line:
361
362```bash
363$ jsesc 'föo ♥ bår 𝌆 baz'
364f\xF6o \u2665 b\xE5r \uD834\uDF06 baz
365```
366
367To escape arrays or objects containing string values, use the `-o`/`--object` option:
368
369```bash
370$ jsesc --object '{ "föo": "♥", "bår": "𝌆 baz" }'
371{'f\xF6o':'\u2665','b\xE5r':'\uD834\uDF06 baz'}
372```
373
374To prettify the output in such cases, use the `-p`/`--pretty` option:
375
376```bash
377$ jsesc --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
378{
379 'f\xF6o': '\u2665',
380 'b\xE5r': '\uD834\uDF06 baz'
381}
382```
383
384For valid JSON output, use the `-j`/`--json` option:
385
386```bash
387$ jsesc --json --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
388{
389 "f\u00F6o": "\u2665",
390 "b\u00E5r": "\uD834\uDF06 baz"
391}
392```
393
394Read a local JSON file, escape any non-ASCII symbols, and save the result to a new file:
395
396```bash
397$ jsesc --json --object < data-raw.json > data-escaped.json
398```
399
400Or do the same with an online JSON file:
401
402```bash
403$ curl -sL "http://git.io/aorKgQ" | jsesc --json --object > data-escaped.json
404```
405
406See `jsesc --help` for the full list of options.
407
408## Support
409
410As of v3.0.0, jsesc supports Node.js v6+ only.
411
412Older 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/).
413
414## Author
415
416| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
417|---|
418| [Mathias Bynens](https://mathiasbynens.be/) |
419
420## License
421
422This library is available under the [MIT](https://mths.be/mit) license.