You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

422 lines
14 KiB

3 months ago
  1. # jsesc
  2. Given some data, _jsesc_ returns a stringified representation of that data. jsesc is similar to `JSON.stringify()` except:
  3. 1. it outputs JavaScript instead of JSON [by default](#json), enabling support for data structures like ES6 maps and sets;
  4. 2. it offers [many options](#api) to customize the output;
  5. 3. its output is ASCII-safe [by default](#minimal), thanks to its use of [escape sequences](https://mathiasbynens.be/notes/javascript-escapes) where needed.
  6. For any input, jsesc generates the shortest possible valid printable-ASCII-only output. [Here’s an online demo.](https://mothereff.in/js-escapes)
  7. 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.
  8. ## Installation
  9. Via [npm](https://www.npmjs.com/):
  10. ```bash
  11. npm install jsesc
  12. ```
  13. In [Node.js](https://nodejs.org/):
  14. ```js
  15. const jsesc = require('jsesc');
  16. ```
  17. ## API
  18. ### `jsesc(value, options)`
  19. 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:
  20. ```js
  21. jsesc('Ich ♥ Bücher');
  22. // → 'Ich \\u2665 B\\xFCcher'
  23. jsesc('foo 𝌆 bar');
  24. // → 'foo \\uD834\\uDF06 bar'
  25. ```
  26. 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.
  27. ```js
  28. // Escaping an array
  29. jsesc([
  30. 'Ich ♥ Bücher', 'foo 𝌆 bar'
  31. ]);
  32. // → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']'
  33. // Escaping an object
  34. jsesc({
  35. 'Ich ♥ Bücher': 'foo 𝌆 bar'
  36. });
  37. // → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}'
  38. ```
  39. The optional `options` argument accepts an object with the following options:
  40. #### `quotes`
  41. 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.
  42. ```js
  43. jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.');
  44. // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
  45. jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
  46. 'quotes': 'single'
  47. });
  48. // → '`Lorem` ipsum "dolor" sit \\\'amet\\\' etc.'
  49. // → "`Lorem` ipsum \"dolor\" sit \\'amet\\' etc."
  50. ```
  51. If you want to use the output as part of a string literal wrapped in double quotes, set the `quotes` option to `'double'`.
  52. ```js
  53. jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
  54. 'quotes': 'double'
  55. });
  56. // → '`Lorem` ipsum \\"dolor\\" sit \'amet\' etc.'
  57. // → "`Lorem` ipsum \\\"dolor\\\" sit 'amet' etc."
  58. ```
  59. If you want to use the output as part of a template literal (i.e. wrapped in backticks), set the `quotes` option to `'backtick'`.
  60. ```js
  61. jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
  62. 'quotes': 'backtick'
  63. });
  64. // → '\\`Lorem\\` ipsum "dolor" sit \'amet\' etc.'
  65. // → "\\`Lorem\\` ipsum \"dolor\" sit 'amet' etc."
  66. // → `\\\`Lorem\\\` ipsum "dolor" sit 'amet' etc.`
  67. ```
  68. This setting also affects the output for arrays and objects:
  69. ```js
  70. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  71. 'quotes': 'double'
  72. });
  73. // → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}'
  74. jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
  75. 'quotes': 'double'
  76. });
  77. // → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]'
  78. ```
  79. #### `numbers`
  80. 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.
  81. ```js
  82. jsesc(42, {
  83. 'numbers': 'binary'
  84. });
  85. // → '0b101010'
  86. jsesc(42, {
  87. 'numbers': 'octal'
  88. });
  89. // → '0o52'
  90. jsesc(42, {
  91. 'numbers': 'decimal'
  92. });
  93. // → '42'
  94. jsesc(42, {
  95. 'numbers': 'hexadecimal'
  96. });
  97. // → '0x2A'
  98. ```
  99. #### `wrap`
  100. 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.
  101. ```js
  102. jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  103. 'quotes': 'single',
  104. 'wrap': true
  105. });
  106. // → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\''
  107. // → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'"
  108. jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  109. 'quotes': 'double',
  110. 'wrap': true
  111. });
  112. // → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."'
  113. // → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\""
  114. ```
  115. #### `es6`
  116. 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`).
  117. ```js
  118. // By default, the `es6` option is disabled:
  119. jsesc('foo 𝌆 bar 💩 baz');
  120. // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'
  121. // To explicitly disable it:
  122. jsesc('foo 𝌆 bar 💩 baz', {
  123. 'es6': false
  124. });
  125. // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'
  126. // To enable it:
  127. jsesc('foo 𝌆 bar 💩 baz', {
  128. 'es6': true
  129. });
  130. // → 'foo \\u{1D306} bar \\u{1F4A9} baz'
  131. ```
  132. #### `escapeEverything`
  133. 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.
  134. ```js
  135. jsesc('lolwat"foo\'bar', {
  136. 'escapeEverything': true
  137. });
  138. // → '\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72'
  139. // → "\\x6C\\x6F\\x6C\\x77\\x61\\x74\\\"\\x66\\x6F\\x6F\\'\\x62\\x61\\x72"
  140. ```
  141. This setting also affects the output for string literals within arrays and objects.
  142. #### `minimal`
  143. 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:
  144. * U+0000 `\0`
  145. * U+0008 `\b`
  146. * U+0009 `\t`
  147. * U+000A `\n`
  148. * U+000C `\f`
  149. * U+000D `\r`
  150. * U+005C `\\`
  151. * U+2028 `\u2028`
  152. * U+2029 `\u2029`
  153. * whatever symbol is being used for wrapping string literals (based on [the `quotes` option](#quotes))
  154. * [lone surrogates](https://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)
  155. Note: with this option enabled, jsesc output is no longer guaranteed to be ASCII-safe.
  156. ```js
  157. jsesc('foo\u2029bar\nbaz©qux𝌆flops', {
  158. 'minimal': false
  159. });
  160. // → 'foo\\u2029bar\\nbaz©qux𝌆flops'
  161. ```
  162. #### `isScriptContext`
  163. 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.
  164. ```js
  165. jsesc('foo</script>bar', {
  166. 'isScriptContext': true
  167. });
  168. // → 'foo<\\/script>bar'
  169. ```
  170. #### `compact`
  171. 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.
  172. ```js
  173. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  174. 'compact': true // this is the default
  175. });
  176. // → '{\'Ich \u2665 B\xFCcher\':\'foo \uD834\uDF06 bar\'}'
  177. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  178. 'compact': false
  179. });
  180. // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
  181. jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
  182. 'compact': false
  183. });
  184. // → '[\n\t\'Ich \u2665 B\xFCcher\',\n\t\'foo \uD834\uDF06 bar\'\n]'
  185. ```
  186. This setting has no effect on the output for strings.
  187. #### `indent`
  188. The `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.
  189. ```js
  190. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  191. 'compact': false,
  192. 'indent': '\t' // this is the default
  193. });
  194. // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
  195. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  196. 'compact': false,
  197. 'indent': ' '
  198. });
  199. // → '{\n \'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
  200. jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
  201. 'compact': false,
  202. 'indent': ' '
  203. });
  204. // → '[\n \'Ich \u2665 B\xFCcher\',\n\ t\'foo \uD834\uDF06 bar\'\n]'
  205. ```
  206. This setting has no effect on the output for strings.
  207. #### `indentLevel`
  208. 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.
  209. ```js
  210. jsesc(['a', 'b', 'c'], {
  211. 'compact': false,
  212. 'indentLevel': 1
  213. });
  214. // → '[\n\t\t\'a\',\n\t\t\'b\',\n\t\t\'c\'\n\t]'
  215. jsesc(['a', 'b', 'c'], {
  216. 'compact': false,
  217. 'indentLevel': 2
  218. });
  219. // → '[\n\t\t\t\'a\',\n\t\t\t\'b\',\n\t\t\t\'c\'\n\t\t]'
  220. ```
  221. #### `json`
  222. 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.
  223. ```js
  224. jsesc('foo\x00bar\xFF\uFFFDbaz', {
  225. 'json': true
  226. });
  227. // → '"foo\\u0000bar\\u00FF\\uFFFDbaz"'
  228. jsesc({ 'foo\x00bar\xFF\uFFFDbaz': 'foo\x00bar\xFF\uFFFDbaz' }, {
  229. 'json': true
  230. });
  231. // → '{"foo\\u0000bar\\u00FF\\uFFFDbaz":"foo\\u0000bar\\u00FF\\uFFFDbaz"}'
  232. jsesc([ 'foo\x00bar\xFF\uFFFDbaz', 'foo\x00bar\xFF\uFFFDbaz' ], {
  233. 'json': true
  234. });
  235. // → '["foo\\u0000bar\\u00FF\\uFFFDbaz","foo\\u0000bar\\u00FF\\uFFFDbaz"]'
  236. // Values that are acceptable in JSON but aren’t strings, arrays, or object
  237. // literals can’t be escaped, so they’ll just be preserved:
  238. jsesc([ 'foo\x00bar', [1, '©', { 'foo': true, 'qux': null }], 42 ], {
  239. 'json': true
  240. });
  241. // → '["foo\\u0000bar",[1,"\\u00A9",{"foo":true,"qux":null}],42]'
  242. // Values that aren’t allowed in JSON are run through `JSON.stringify()`:
  243. jsesc([ undefined, -Infinity ], {
  244. 'json': true
  245. });
  246. // → '[null,null]'
  247. ```
  248. **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/).
  249. #### `lowercaseHex`
  250. 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.
  251. ```js
  252. jsesc('Ich ♥ Bücher', {
  253. 'lowercaseHex': true
  254. });
  255. // → 'Ich \\u2665 B\\xfccher'
  256. // ^^
  257. jsesc(42, {
  258. 'numbers': 'hexadecimal',
  259. 'lowercaseHex': true
  260. });
  261. // → '0x2a'
  262. // ^^
  263. ```
  264. ### `jsesc.version`
  265. A string representing the semantic version number.
  266. ### Using the `jsesc` binary
  267. To use the `jsesc` binary in your shell, simply install jsesc globally using npm:
  268. ```bash
  269. npm install -g jsesc
  270. ```
  271. After that you’re able to escape strings from the command line:
  272. ```bash
  273. $ jsesc 'föo ♥ bår 𝌆 baz'
  274. f\xF6o \u2665 b\xE5r \uD834\uDF06 baz
  275. ```
  276. To escape arrays or objects containing string values, use the `-o`/`--object` option:
  277. ```bash
  278. $ jsesc --object '{ "föo": "♥", "bår": "𝌆 baz" }'
  279. {'f\xF6o':'\u2665','b\xE5r':'\uD834\uDF06 baz'}
  280. ```
  281. To prettify the output in such cases, use the `-p`/`--pretty` option:
  282. ```bash
  283. $ jsesc --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
  284. {
  285. 'f\xF6o': '\u2665',
  286. 'b\xE5r': '\uD834\uDF06 baz'
  287. }
  288. ```
  289. For valid JSON output, use the `-j`/`--json` option:
  290. ```bash
  291. $ jsesc --json --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
  292. {
  293. "f\u00F6o": "\u2665",
  294. "b\u00E5r": "\uD834\uDF06 baz"
  295. }
  296. ```
  297. Read a local JSON file, escape any non-ASCII symbols, and save the result to a new file:
  298. ```bash
  299. $ jsesc --json --object < data-raw.json > data-escaped.json
  300. ```
  301. Or do the same with an online JSON file:
  302. ```bash
  303. $ curl -sL "http://git.io/aorKgQ" | jsesc --json --object > data-escaped.json
  304. ```
  305. See `jsesc --help` for the full list of options.
  306. ## Support
  307. As of v3.0.0, jsesc supports Node.js v6+ only.
  308. 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/).
  309. ## Author
  310. | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
  311. |---|
  312. | [Mathias Bynens](https://mathiasbynens.be/) |
  313. ## License
  314. This library is available under the [MIT](https://mths.be/mit) license.