GithubHelp home page GithubHelp logo

mathiasbynens / jsesc Goto Github PK

View Code? Open in Web Editor NEW
713.0 16.0 53.0 269 KB

Given some data, jsesc returns the shortest possible stringified & ASCII-safe representation of that data.

Home Page: https://mths.be/jsesc

License: MIT License

JavaScript 97.56% HTML 2.44%
code-generation ecmascript javascript stringify json ascii-safe unicode escape-sequences escape

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

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

string-escape on npm

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

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

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.

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?

'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

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

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.

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}"'

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

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.

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?

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.

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.

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.

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

Live example?

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

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

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' : '');

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.

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.

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.

Occurences vs occurrences

Hi,

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

Thanks!

Empty arrays / objects

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

[
]

{
}

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.

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.