21cb2645862237e20f7ff145b053631e139041d68c7727314d1a14841c3a18a47438f90968743f4befd1ba2c5e249dd2a2909f7d930999f3b031d15214fcbc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. # jsesc [![Build status](https://travis-ci.org/mathiasbynens/jsesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/jsesc) [![Code coverage status](http://img.shields.io/coveralls/mathiasbynens/jsesc/master.svg)](https://coveralls.io/r/mathiasbynens/jsesc) [![Dependency status](https://gemnasium.com/mathiasbynens/jsesc.svg)](https://gemnasium.com/mathiasbynens/jsesc)
  2. This is a JavaScript library for [escaping JavaScript strings](http://mathiasbynens.be/notes/javascript-escapes) while generating the shortest possible valid ASCII-only output. [Here’s an online demo.](http://mothereff.in/js-escapes)
  3. This can be used to avoid [mojibake](http://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](http://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)) to a JavaScript parser or an UTF-8 encoder, respectively.
  4. Feel free to fork if you see possible improvements!
  5. ## Installation
  6. Via [Bower](http://bower.io/):
  7. ```bash
  8. bower install jsesc
  9. ```
  10. Via [Component](https://github.com/component/component):
  11. ```bash
  12. component install mathiasbynens/jsesc
  13. ```
  14. Via [npm](http://npmjs.org/):
  15. ```bash
  16. npm install jsesc
  17. ```
  18. In a browser:
  19. ```html
  20. <script src="jsesc.js"></script>
  21. ```
  22. In [Node.js](http://nodejs.org/) and [RingoJS](http://ringojs.org/):
  23. ```js
  24. var jsesc = require('jsesc');
  25. ```
  26. In [Narwhal](http://narwhaljs.org/):
  27. ```js
  28. var jsesc = require('jsesc').jsesc;
  29. ```
  30. In [Rhino](http://www.mozilla.org/rhino/):
  31. ```js
  32. load('jsesc.js');
  33. ```
  34. Using an AMD loader like [RequireJS](http://requirejs.org/):
  35. ```js
  36. require(
  37. {
  38. 'paths': {
  39. 'jsesc': 'path/to/jsesc'
  40. }
  41. },
  42. ['jsesc'],
  43. function(jsesc) {
  44. console.log(jsesc);
  45. }
  46. );
  47. ```
  48. ## API
  49. ### `jsesc(value, options)`
  50. 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](http://mathiasbynens.be/notes/javascript-escapes). The first supported value type is strings:
  51. ```js
  52. jsesc('Ich ♥ Bücher');
  53. // → 'Ich \\u2665 B\\xFCcher'
  54. jsesc('foo 𝌆 bar');
  55. // → 'foo \\uD834\\uDF06 bar'
  56. ```
  57. Instead of a string, the `value` can also be an array, or an object. In such cases, `jsesc` will return a stringified version of the value where any characters that are not printable ASCII symbols are escaped in the same way.
  58. ```js
  59. // Escaping an array
  60. jsesc([
  61. 'Ich ♥ Bücher', 'foo 𝌆 bar'
  62. ]);
  63. // → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']'
  64. // Escaping an object
  65. jsesc({
  66. 'Ich ♥ Bücher': 'foo 𝌆 bar'
  67. });
  68. // → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}'
  69. ```
  70. The optional `options` argument accepts an object with the following options:
  71. #### `quotes`
  72. The default value for the `quotes` option is `'single'`. This means that any occurences of `'` in the input string will be escaped as `\'`, so that the output can be used in a string literal wrapped in single quotes.
  73. ```js
  74. jsesc('Lorem ipsum "dolor" sit \'amet\' etc.');
  75. // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
  76. jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  77. 'quotes': 'single'
  78. });
  79. // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
  80. // → "Lorem ipsum \"dolor\" sit \\'amet\\' etc."
  81. ```
  82. If you want to use the output as part of a string literal wrapped in double quotes, set the `quotes` option to `'double'`.
  83. ```js
  84. jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  85. 'quotes': 'double'
  86. });
  87. // → 'Lorem ipsum \\"dolor\\" sit \'amet\' etc.'
  88. // → "Lorem ipsum \\\"dolor\\\" sit 'amet' etc."
  89. ```
  90. This setting also affects the output for arrays and objects:
  91. ```js
  92. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  93. 'quotes': 'double'
  94. });
  95. // → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}'
  96. jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
  97. 'quotes': 'double'
  98. });
  99. // → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]'
  100. ```
  101. #### `wrap`
  102. The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output will be a valid JavaScript string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting.
  103. ```js
  104. jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  105. 'quotes': 'single',
  106. 'wrap': true
  107. });
  108. // → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\''
  109. // → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'"
  110. jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  111. 'quotes': 'double',
  112. 'wrap': true
  113. });
  114. // → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."'
  115. // → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\""
  116. ```
  117. #### `es6`
  118. The `es6` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any astral Unicode symbols in the input will be escaped using [ECMAScript 6 Unicode code point escape sequences](http://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`).
  119. ```js
  120. // By default, the `es6` option is disabled:
  121. jsesc('foo 𝌆 bar 💩 baz');
  122. // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'
  123. // To explicitly disable it:
  124. jsesc('foo 𝌆 bar 💩 baz', {
  125. 'es6': false
  126. });
  127. // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'
  128. // To enable it:
  129. jsesc('foo 𝌆 bar 💩 baz', {
  130. 'es6': true
  131. });
  132. // → 'foo \\u{1D306} bar \\u{1F4A9} baz'
  133. ```
  134. #### `escapeEverything`
  135. The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output will be escaped, even printable ASCII symbols.
  136. ```js
  137. jsesc('lolwat"foo\'bar', {
  138. 'escapeEverything': true
  139. });
  140. // → '\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72'
  141. // → "\\x6C\\x6F\\x6C\\x77\\x61\\x74\\\"\\x66\\x6F\\x6F\\'\\x62\\x61\\x72"
  142. ```
  143. This setting also affects the output for arrays and objects:
  144. ```js
  145. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  146. 'escapeEverything': true
  147. });
  148. // → '{\'\x49\x63\x68\x20\u2665\x20\x42\xFC\x63\x68\x65\x72\':\'\x66\x6F\x6F\x20\uD834\uDF06\x20\x62\x61\x72\'}'
  149. // → "{'\x49\x63\x68\x20\u2665\x20\x42\xFC\x63\x68\x65\x72':'\x66\x6F\x6F\x20\uD834\uDF06\x20\x62\x61\x72'}"
  150. jsesc([ 'Ich ♥ Bücher': 'foo 𝌆 bar' ], {
  151. 'escapeEverything': true
  152. });
  153. // → '[\'\x49\x63\x68\x20\u2665\x20\x42\xFC\x63\x68\x65\x72\',\'\x66\x6F\x6F\x20\uD834\uDF06\x20\x62\x61\x72\']'
  154. ```
  155. #### `compact`
  156. The `compact` option takes a boolean value (`true` or `false`), and defaults to `true` (enabled). When enabled, the output for arrays and objects will be as compact as possible; it won’t be formatted nicely.
  157. ```js
  158. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  159. 'compact': true // this is the default
  160. });
  161. // → '{\'Ich \u2665 B\xFCcher\':\'foo \uD834\uDF06 bar\'}'
  162. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  163. 'compact': false
  164. });
  165. // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
  166. jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
  167. 'compact': false
  168. });
  169. // → '[\n\t\'Ich \u2665 B\xFCcher\',\n\t\'foo \uD834\uDF06 bar\'\n]'
  170. ```
  171. This setting has no effect on the output for strings.
  172. #### `indent`
  173. 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.
  174. ```js
  175. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  176. 'compact': false,
  177. 'indent': '\t' // this is the default
  178. });
  179. // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
  180. jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  181. 'compact': false,
  182. 'indent': ' '
  183. });
  184. // → '{\n \'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
  185. jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
  186. 'compact': false,
  187. 'indent': ' '
  188. });
  189. // → '[\n \'Ich \u2665 B\xFCcher\',\n\ t\'foo \uD834\uDF06 bar\'\n]'
  190. ```
  191. This setting has no effect on the output for strings.
  192. #### `json`
  193. 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](http://mathiasbynens.be/notes/javascript-escapes#hexadecimal) and [the `\v` or `\0` escape sequences](http://mathiasbynens.be/notes/javascript-escapes#single) will not be 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.
  194. ```js
  195. jsesc('foo\x00bar\xFF\uFFFDbaz', {
  196. 'json': true
  197. });
  198. // → '"foo\\u0000bar\\u00FF\\uFFFDbaz"'
  199. jsesc({ 'foo\x00bar\xFF\uFFFDbaz': 'foo\x00bar\xFF\uFFFDbaz' }, {
  200. 'json': true
  201. });
  202. // → '{"foo\\u0000bar\\u00FF\\uFFFDbaz":"foo\\u0000bar\\u00FF\\uFFFDbaz"}'
  203. jsesc([ 'foo\x00bar\xFF\uFFFDbaz', 'foo\x00bar\xFF\uFFFDbaz' ], {
  204. 'json': true
  205. });
  206. // → '["foo\\u0000bar\\u00FF\\uFFFDbaz","foo\\u0000bar\\u00FF\\uFFFDbaz"]'
  207. // Values that are acceptable in JSON but aren’t strings, arrays, or object
  208. // literals can’t be escaped, so they’ll just be preserved:
  209. jsesc([ 'foo\x00bar', [1, '©', { 'foo': true, 'qux': null }], 42 ], {
  210. 'json': true
  211. });
  212. // → '["foo\\u0000bar",[1,"\\u00A9",{"foo":true,"qux":null}],42]'
  213. // Values that aren’t allowed in JSON are run through `JSON.stringify()`:
  214. jsesc([ undefined, -Infinity ], {
  215. 'json': true
  216. });
  217. // → '[null,null]'
  218. ```
  219. **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/).
  220. ### `jsesc.version`
  221. A string representing the semantic version number.
  222. ### Using the `jsesc` binary
  223. To use the `jsesc` binary in your shell, simply install jsesc globally using npm:
  224. ```bash
  225. npm install -g jsesc
  226. ```
  227. After that you will be able to escape strings from the command line:
  228. ```bash
  229. $ jsesc 'föo ♥ bår 𝌆 baz'
  230. f\xF6o \u2665 b\xE5r \uD834\uDF06 baz
  231. ```
  232. To escape arrays or objects containing string values, use the `-o`/`--object` option:
  233. ```bash
  234. $ jsesc --object '{ "föo": "♥", "bår": "𝌆 baz" }'
  235. {'f\xF6o':'\u2665','b\xE5r':'\uD834\uDF06 baz'}
  236. ```
  237. To prettify the output in such cases, use the `-p`/`--pretty` option:
  238. ```bash
  239. $ jsesc --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
  240. {
  241. 'f\xF6o': '\u2665',
  242. 'b\xE5r': '\uD834\uDF06 baz'
  243. }
  244. ```
  245. For valid JSON output, use the `-j`/`--json` option:
  246. ```bash
  247. $ jsesc --json --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
  248. {
  249. "f\u00F6o": "\u2665",
  250. "b\u00E5r": "\uD834\uDF06 baz"
  251. }
  252. ```
  253. Read a local JSON file, escape any non-ASCII symbols, and save the result to a new file:
  254. ```bash
  255. $ jsesc --json --object < data-raw.json > data-escaped.json
  256. ```
  257. Or do the same with an online JSON file:
  258. ```bash
  259. $ curl -sL "http://git.io/aorKgQ" | jsesc --json --object > data-escaped.json
  260. ```
  261. See `jsesc --help` for the full list of options.
  262. ## Support
  263. This library has been tested in at least Chrome 27-29, Firefox 3-22, Safari 4-6, Opera 10-12, IE 6-10, Node.js v0.10.0, Narwhal 0.3.2, RingoJS 0.8-0.9, PhantomJS 1.9.0, and Rhino 1.7RC4.
  264. **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](http://bestiejs.github.io/json3/).
  265. ## Unit tests & code coverage
  266. After cloning this repository, run `npm install` to install the dependencies needed for development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`.
  267. Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, and web browsers as well, use `grunt test`.
  268. To generate the code coverage report, use `grunt cover`.
  269. ## Author
  270. | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
  271. |---|
  272. | [Mathias Bynens](http://mathiasbynens.be/) |
  273. ## License
  274. This library is available under the [MIT](http://mths.be/mit) license.