mathiasbynens / jsesc Goto Github PK
View Code? Open in Web Editor NEWGiven some data, jsesc returns the shortest possible stringified & ASCII-safe representation of that data.
Home Page: https://mths.be/jsesc
License: MIT License
Given some data, jsesc returns the shortest possible stringified & ASCII-safe representation of that data.
Home Page: https://mths.be/jsesc
License: MIT License
$ jsesc --pretty '[]'
[
]
$ jsesc --pretty '{}'
{
}
Avoid adding the \n\n
to the output for empty objects or arrays.
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 ...
I am developing an android app and I need to unescape the string.
When I install string-escape
it does not include an index.js
... is it deprecated?
mssql non unicode columns support extended ascii (code can be from 0-255)
Please add an option for not escaping extended ascii chars
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.
$ 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?
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
For example, jsesc doesn’t skip undefined
properties, and it doesn’t make use of toJSON
:
var obj = {
'toJSON': function() {
return 'wat';
}
};
var x = {
'lol': obj
};
console.log([
JSON.stringify(x),
jsesc(x, { 'json': true })
]);
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)
.
For integers we could use something like this:
const string = '1234567890';
string.replace(/(.(?=(.{3})+$))/g, '$1_');
// -> '1_234_567_890'
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.
I recently attempted to use jsesc in the browser, but ran into the following issue: facebook/create-react-app#2891 (comment)
Are there any plans to publish this library pre-compiled for browsers?
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}"'
const object = {};
^^^^^
SyntaxError: Use of const in strict mode.
This option would use the \u{XXXXXX}
-style escape sequences for astral symbols, rather than explicit surrogate pairs.
I wonder if there is a way no to shorten the unicode codes with \xYY
format and keep \u00YY
format instead. \xYY
format is not supported by some tools in some languages.
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
…like on http://mothereff.in/js-escapes.
Any ideas for the option name? Perhaps escapeAll: true
to escape all symbols (even A-Z
etc.)?
Feature request:
// Current behavior
> jsesc({ key: 'value' }, { minimal: true })
'{\'key\':\'value\'}'
// Preferred behavior
> jsesc({ key: 'value' }, { minimal: true })
'{key:\'value\'}'
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.
Hello, I've found that some of your files in this repo is still using https://git.io/, and this service will be discontinued in the future. (ref: Git.io deprecation)
Theses files are: README.md
This is an automated message from NPMMirror(https://github.com/npmmirror), a bot developed by Nova Kwok(https://github.com/n0vad3v).
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?
Line 6 in 30be7a6
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.
Will there be component support?
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 %%%% -> %%
wrap: true
would wrap the output in the quotes of the type specified by the quotes
option.
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.
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.
Handy to have them in the readme too
Sorry if this is off topic
i see this page
https://mathiasbynens.be/notes/javascript-escapes
however i do not see a repo for those posts
do you have some "notes" repo somewhere?
Could we get a Heroku-like example online, for quick copy + paste escaping?
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.
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.
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' : '');
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.
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.
Does this have an unescape function as well?
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.
Hi,
the debian tool "lintian" detected a double typo in jsesc.1 : "occurrences" is the right spelling.
Thanks!
With compact: false
, they should probably stringify to []
& {}
rather than…
[
]
{
}
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.
E.g.
jsesc(/\B/); // '/B/'
The output should be '/\\B/'
.
We should get rid of eval
and parse any escape sequences in regex.source
ourselves.
Is there any way to revert back the escaped string?
This would be useful in situations like jsperf/jsperf.com#109.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.