Git Product home page Git Product logo

jsesc's Introduction

jsesc Build status Code coverage status

Given some data, jsesc returns a stringified representation of that data. jsesc is similar to JSON.stringify() except:

  1. it outputs JavaScript instead of JSON by default, enabling support for data structures like ES6 maps and sets;
  2. it offers many options to customize the output;
  3. its output is ASCII-safe by default, thanks to its use of escape sequences where needed.

For any input, jsesc generates the shortest possible valid printable-ASCII-only output. Here’s an online demo.

jsesc’s output can be used instead of JSON.stringify’s to avoid mojibake and other encoding issues, or even to avoid errors when passing JSON-formatted data (which may contain U+2028 LINE SEPARATOR, U+2029 PARAGRAPH SEPARATOR, or lone surrogates) to a JavaScript parser or an UTF-8 encoder.

Installation

Via npm:

npm install jsesc

In Node.js:

const jsesc = require('jsesc');

API

jsesc(value, options)

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. The first supported value type is strings:

jsesc('Ich ♥ Bücher');
// → 'Ich \\u2665 B\\xFCcher'

jsesc('foo 𝌆 bar');
// → 'foo \\uD834\\uDF06 bar'

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.

// Escaping an array
jsesc([
  'Ich ♥ Bücher', 'foo 𝌆 bar'
]);
// → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']'

// Escaping an object
jsesc({
  'Ich ♥ Bücher': 'foo 𝌆 bar'
});
// → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}'

The optional options argument accepts an object with the following options:

quotes

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.

jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.');
// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'

jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
  'quotes': 'single'
});
// → '`Lorem` ipsum "dolor" sit \\\'amet\\\' etc.'
// → "`Lorem` ipsum \"dolor\" sit \\'amet\\' etc."

If you want to use the output as part of a string literal wrapped in double quotes, set the quotes option to 'double'.

jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
  'quotes': 'double'
});
// → '`Lorem` ipsum \\"dolor\\" sit \'amet\' etc.'
// → "`Lorem` ipsum \\\"dolor\\\" sit 'amet' etc."

If you want to use the output as part of a template literal (i.e. wrapped in backticks), set the quotes option to 'backtick'.

jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
  'quotes': 'backtick'
});
// → '\\`Lorem\\` ipsum "dolor" sit \'amet\' etc.'
// → "\\`Lorem\\` ipsum \"dolor\" sit 'amet' etc."
// → `\\\`Lorem\\\` ipsum "dolor" sit 'amet' etc.`

This setting also affects the output for arrays and objects:

jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  'quotes': 'double'
});
// → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}'

jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
  'quotes': 'double'
});
// → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]'

numbers

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.

jsesc(42, {
  'numbers': 'binary'
});
// → '0b101010'

jsesc(42, {
  'numbers': 'octal'
});
// → '0o52'

jsesc(42, {
  'numbers': 'decimal'
});
// → '42'

jsesc(42, {
  'numbers': 'hexadecimal'
});
// → '0x2A'

wrap

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.

jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  'quotes': 'single',
  'wrap': true
});
// → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\''
// → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'"

jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  'quotes': 'double',
  'wrap': true
});
// → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."'
// → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\""

es6

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 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).

// By default, the `es6` option is disabled:
jsesc('foo 𝌆 bar 💩 baz');
// → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'

// To explicitly disable it:
jsesc('foo 𝌆 bar 💩 baz', {
  'es6': false
});
// → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'

// To enable it:
jsesc('foo 𝌆 bar 💩 baz', {
  'es6': true
});
// → 'foo \\u{1D306} bar \\u{1F4A9} baz'

escapeEverything

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.

jsesc('lolwat"foo\'bar', {
  'escapeEverything': true
});
// → '\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72'
// → "\\x6C\\x6F\\x6C\\x77\\x61\\x74\\\"\\x66\\x6F\\x6F\\'\\x62\\x61\\x72"

This setting also affects the output for string literals within arrays and objects.

minimal

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:

  • U+0000 \0
  • U+0008 \b
  • U+0009 \t
  • U+000A \n
  • U+000C \f
  • U+000D \r
  • U+005C \\
  • U+2028 \u2028
  • U+2029 \u2029
  • whatever symbol is being used for wrapping string literals (based on the quotes option)
  • lone surrogates

Note: with this option enabled, jsesc output is no longer guaranteed to be ASCII-safe.

jsesc('foo\u2029bar\nbaz©qux𝌆flops', {
  'minimal': false
});
// → 'foo\\u2029bar\\nbaz©qux𝌆flops'

isScriptContext

The isScriptContext option takes a boolean value (true or false), and defaults to false (disabled). When enabled, occurrences of </script and </style in the output are escaped as <\/script and <\/style, and <!-- 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.

jsesc('foo</script>bar', {
  'isScriptContext': true
});
// → 'foo<\\/script>bar'

compact

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.

jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  'compact': true // this is the default
});
// → '{\'Ich \u2665 B\xFCcher\':\'foo \uD834\uDF06 bar\'}'

jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  'compact': false
});
// → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'

jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
  'compact': false
});
// → '[\n\t\'Ich \u2665 B\xFCcher\',\n\t\'foo \uD834\uDF06 bar\'\n]'

This setting has no effect on the output for strings.

indent

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.

jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  'compact': false,
  'indent': '\t' // this is the default
});
// → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'

jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
  'compact': false,
  'indent': '  '
});
// → '{\n  \'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'

jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
  'compact': false,
  'indent': '  '
});
// → '[\n  \'Ich \u2665 B\xFCcher\',\n\  t\'foo \uD834\uDF06 bar\'\n]'

This setting has no effect on the output for strings.

indentLevel

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 is repeated.

jsesc(['a', 'b', 'c'], {
  'compact': false,
  'indentLevel': 1
});
// → '[\n\t\t\'a\',\n\t\t\'b\',\n\t\t\'c\'\n\t]'

jsesc(['a', 'b', 'c'], {
  'compact': false,
  'indentLevel': 2
});
// → '[\n\t\t\t\'a\',\n\t\t\t\'b\',\n\t\t\t\'c\'\n\t\t]'

json

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 and the \v or \0 escape sequences 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.

jsesc('foo\x00bar\xFF\uFFFDbaz', {
  'json': true
});
// → '"foo\\u0000bar\\u00FF\\uFFFDbaz"'

jsesc({ 'foo\x00bar\xFF\uFFFDbaz': 'foo\x00bar\xFF\uFFFDbaz' }, {
  'json': true
});
// → '{"foo\\u0000bar\\u00FF\\uFFFDbaz":"foo\\u0000bar\\u00FF\\uFFFDbaz"}'

jsesc([ 'foo\x00bar\xFF\uFFFDbaz', 'foo\x00bar\xFF\uFFFDbaz' ], {
  'json': true
});
// → '["foo\\u0000bar\\u00FF\\uFFFDbaz","foo\\u0000bar\\u00FF\\uFFFDbaz"]'

// Values that are acceptable in JSON but aren’t strings, arrays, or object
// literals can’t be escaped, so they’ll just be preserved:
jsesc([ 'foo\x00bar', [1, '©', { 'foo': true, 'qux': null }], 42 ], {
  'json': true
});
// → '["foo\\u0000bar",[1,"\\u00A9",{"foo":true,"qux":null}],42]'
// Values that aren’t allowed in JSON are run through `JSON.stringify()`:
jsesc([ undefined, -Infinity ], {
  'json': true
});
// → '[null,null]'

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.

lowercaseHex

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) in the output are in lowercase.

jsesc('Ich ♥ Bücher', {
  'lowercaseHex': true
});
// → 'Ich \\u2665 B\\xfccher'
//                    ^^

jsesc(42, {
  'numbers': 'hexadecimal',
  'lowercaseHex': true
});
// → '0x2a'
//      ^^

jsesc.version

A string representing the semantic version number.

Using the jsesc binary

To use the jsesc binary in your shell, simply install jsesc globally using npm:

npm install -g jsesc

After that you’re able to escape strings from the command line:

$ jsesc 'föo ♥ bår 𝌆 baz'
f\xF6o \u2665 b\xE5r \uD834\uDF06 baz

To escape arrays or objects containing string values, use the -o/--object option:

$ jsesc --object '{ "föo": "♥", "bår": "𝌆 baz" }'
{'f\xF6o':'\u2665','b\xE5r':'\uD834\uDF06 baz'}

To prettify the output in such cases, use the -p/--pretty option:

$ jsesc --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
{
  'f\xF6o': '\u2665',
  'b\xE5r': '\uD834\uDF06 baz'
}

For valid JSON output, use the -j/--json option:

$ jsesc --json --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
{
  "f\u00F6o": "\u2665",
  "b\u00E5r": "\uD834\uDF06 baz"
}

Read a local JSON file, escape any non-ASCII symbols, and save the result to a new file:

$ jsesc --json --object < data-raw.json > data-escaped.json

Or do the same with an online JSON file:

$ curl -sL "http://git.io/aorKgQ" | jsesc --json --object > data-escaped.json

See jsesc --help for the full list of options.

Support

As of v3.0.0, jsesc supports Node.js v6+ only.

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.

Author

twitter/mathias
Mathias Bynens

License

This library is available under the MIT license.

jsesc's People

Contributors

almet avatar boldewyn avatar evan-dickinson avatar isidrok avatar jhubble avatar jridgewell avatar mathiasbynens avatar sonneveld avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsesc's Issues

Is this a super-set of js-string-escape?

Hey Mathias, I just came across your library - very nice!

Am I correct that this library is basically a super-set of js-string-escape, modulo the quotes option, so I can add a big "use jsesc" notice at the top of the js-string-escape README?

(jsesc basically passes js-string-escape's test suite for strings: https://github.com/joliss/js-string-escape/tree/jsesc)

Looking at the jsesc test suite, it looks like the security (for untrusted strings) and invariance guarantees hold for jsesc as well, correct?

Node 4.5.0 fails to run jsesc

I have a project which depends on gulp-angular-templatecache which in turn depends on jsesc. Using Node 4.4.7 it works fine, but after upgrading to Node 4.5.0 it fails with three errors:

  • SyntaxError: Use of const in strict mode. line 3, const object = {};
  • SyntaxError: Unexpected token in line 6, for (const key in object) {
  • SyntaxError: Unexpected identifier line 25, let index = -1;

By removing strict mode, replacing every instance of let with var, and converting key to a var in the for-loop it worked for me. Of course I assume you don't want to remove strict mode, so another solution is probably better suited.

Make `jsesc --object` accept non-JSON-formatted data as well

$ jsesc --object '{"foo":42}' 
{'foo':42}

$ jsesc --object "{'foo':42}"
Unexpected token '

Error: failed to escape.
If you think this is a bug in jsesc, please report it:
https://github.com/mathiasbynens/jsesc/issues/new

Stack trace using [email protected]:

SyntaxError: Unexpected token '
    at Object.parse (native)
    at /usr/local/share/npm/lib/node_modules/jsesc/bin/jsesc:85:20
    at Array.forEach (native)
    at main (/usr/local/share/npm/lib/node_modules/jsesc/bin/jsesc:49:11)
    at /usr/local/share/npm/lib/node_modules/jsesc/bin/jsesc:110:3
    at Object.<anonymous> (/usr/local/share/npm/lib/node_modules/jsesc/bin/jsesc:133:2)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)

This is currently by design, since we use JSON.parse(). But maybe we could use something like @espadrine’s localeval instead?

issue in parsing string to json

My code is:

var jsesc = require('jsesc');

var jsonText = '{"account_id":111,"account_name":"test","interface_id":2,"request_id":0,"message_id":"6a23bbbe-1cfd-4ba5-8dfd-b3b7abb86576","source_addr":"Test TNT","destination_addr":"96892000730","coding":2,"concatenation":1,"message_text":"S3rvT3L20130NVBQakoiYHello, I hope you have a nice day. @\u0002#%!&\\/)(=?*+,","UDH":"","flash":0,"validaty_period":1440,"delivery_time":1440,"smpp_port":2012,"registered_delivery":1,"dlr_ip":"10.158.36.200","dlr_port":2051,"submit_sm_start_timestamp":"2015-01-06T05:40:05.042"}'

var jsonOpject = JSON.parse(jsesc(jsonText, {'json': true}));

console.log(jsonOpject.message_id);

The result is:

undefined

feature: use backticks as string delimiter

input

var s = "some 'thing' ${here}"

expected

`var s = "some 'thing' $\{here}"`

actual

'var s = "some \'thing\' ${here}"'

goal: minimize number of escapes

edit: i was looking for node's util.inspect(object)

var u = require('util')

console.log(u.inspect(`var s = "some 'thing' here"`, { depth: null }))
`var s = "some 'thing' here"`

console.log(u.inspect(`var s = "some 'thing' $\{here}"`, { depth: null }))
'var s = "some \'thing\' ${here}"'

support Date objects

Currently, jsesc produces unsupported code when passed a Date object:

jsesc({ value: new Date() })
// => '{\'value\':Tue Mar 31 2020 18:06:06 GMT-0700 (Pacific Daylight Time)}'

Ideally, this would produce a constructor for that date/time. I'm happy to implement - I'm thinking it'd just use the valueOf unless there's a good argument for using the ISO 8601 format.

enable escaping to extended ascii

mssql non unicode columns support extended ascii (code can be from 0-255)
Please add an option for not escaping extended ascii chars

string-escape on npm

When I install string-escape it does not include an index.js... is it deprecated?

missing = in const declaration

for (const key in object) {
causes Firefox to throw the above error, which can be reproduced by pasting this into Firefox's console.

for (const key in {t:1,x:1}) {
  if (hasOwnProperty.call(object, key)) {
    console.log('Never reaches as the code errors');
  }
}

This makes jsesc unusable with webpack/browserify in those environments without explicitly converting the es6 code into es5.

'Allow newlines' option

jsesc should have an option to allow newline characters:

var escaped = jsesc(string, {newlinesAllowed: true} );

So if the string contains a newline character (\n), it would not be replaced by \\n

Discrepancy between published version and Github version

Hello Mathias, thanks for this great tool! I did find a discrepancy between what is currently published on NPM and what's on Github. When I install the latest from NPM, which seems to be 2.2.0 (verified on the module's package.json), I get the 2.1.0 version of jsesc.js (it's both missing the change to isScriptContext and also has the version of 2.1.0 as the value for jsesc.version).

Am I missing something, or was there just a mixup? Thanks in advance for any help.

Performance for escaping strings

For escaping strings, jsesc is about 10x slower than js-string-escape:

$ time node -e "var escape=require('jsesc'); for (var i = 0; i < 1000000; i++) { escape('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') }"

real    0m2.490s
user    0m2.485s
sys 0m0.024s
$ time node -e "var escape=require('js-string-escape'); for (var i = 0; i < 1000000; i++) { escape('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') }"

real    0m0.217s
user    0m0.170s
sys 0m0.051s

This turns out to be relevant in practice: Building my sample JavaScript app takes twice as long when I use jsesc.

Occurences vs occurrences

Hi,

the debian tool "lintian" detected a double typo in jsesc.1 : "occurrences" is the right spelling.

Thanks!

Escape regular expressions

Here’s how to stringify a regular expression, escaping the source as needed:

var regex = /©/gmi;
var result = '/' + stringEscape(regex.source, options) + '/' +
(regex.global ? 'g' : '') + (regex.ignoreCase ? 'i' : '') + (regex.multiline ? 'm' : '');

detect and throw on cyclic references

For example:

const cyclic = {};
cyclic.cyclic = cyclic;

// RangeError: Maximum call stack size exceeded
jsesc(cyclic);

I think this is typically done by tracking an array of seen values and pushing/popping when entering/exiting a recursive jsesc call. I might be able to implement if acceptable.

Live example?

Could we get a Heroku-like example online, for quick copy + paste escaping?

indent option only is valid when compact is false (!true)

This:

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.

Should be:

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.

Link:
https://github.com/mathiasbynens/jsesc#indent

Don’t replace `\x08` with `\b` in regular expressions

In regular expressions, \b has a different meaning than in strings (where it’s equivalent to '\x08'`):

/\b/.test('\b'); // false
/\x08/.test('\b'); // true

But jsesc incorrectly replaces \x08 in regular expressions with \b:

jsesc(/\x08/); // '/\\b/'

Only these single character escapes have the same meaning in regular expressions as in strings:

\f \n \r \t \v \0

Also see #11: \B, \w, \W, \s, \S, \d, \D, \cM, etc. should be preserved.

Check for existence of Buffer

Hi, I'm using this library inside of a service worker and as there is no Buffer implementation I have to polyfill it although it will never be used.

It would be great if isBuffer checked for the existence of Buffer so the library can be used without problems in environments that don't support it:

// current
const isBuffer = Buffer.isBuffer;

// proposal
const isBuffer = (value) => typeof Buffer !== 'undefined' && Buffer.isBuffer(value)

Can submit a PR if interested in the change.

jsesc reduces consecutive percent signs to a single percent sign

When jsesc operates on a string with two percent signs in a row ("%%") it will reduce the output to a single percent sing ("%").

Examples:
jsesc test%%test -> test%test
jsesc ♥%𝌆%%𝌆 -> \u2665%\uD834\uDF06%\uD834\uDF06
jsesc %%%test -> %%test
jsesc test%%%% -> test%%
jsesc %%%% -> %%

Add `wrap` option

wrap: true would wrap the output in the quotes of the type specified by the quotes option.

option for forcing `longhand`

Would it be possible to add an option to always return the longhand version of the match? Enabling the json flag forces longhand as well, but has other consequences.

I'm trying to use this module to verify webhook events sent by Facebook and in order to calculate the correct shasum, I need the longform of the converted characters.

Usage of string.prototype.repeat breaks IE11

When using jsesc inside the browser context the usage of string.prototype.repeat breaks IE11. It results in a TypeError: Object doesn't support property or method 'repeat'. Is it a conscious decision not to support ES5/IE11 with this library? I think a polyfill or transpilation to ES5 Javascript would solve the problem ...

Map and Set included in JSON output

As I understand it, json tries to ensure that the output is JSON-compatible, at least in the types supported. It seems that Map and Set don't comply with this:

jsesc({ set: new Set([12]), map: new Map([['a', 'b']]) }, { json: true })
// => '{"set":new Set([12]),"map":new Map([["a","b"]])}'

JSON.parse encounters a SyntaxError when attempting to interpret this output, which seems undesirable.

Add `json` option?

This would be like JSON.stringify(string) except it would actually escape non-ASCII symbols using only the escape sequences supported by JSON.


Better (?) idea: we could just overload the stringEscape function so stringEscape(object) acts different than stringEscape(string).

Add option to whitelist certain characters

Would be nice to add an option to whitelist certain characters you don't want escaped for example: 'whitelist': 'äöüß' so jsesc ignores these but escapes everything else.

Empty arrays / objects

With compact: false, they should probably stringify to [] & {} rather than…

[
]

{
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.