package
Escape strings for use as JavaScript string literals
npm install js-string-escapeGitHub-flavored package documentation.
Across all versions, last 30 days.
15,702,480 in 30 days
Runtime metadata.
Tagged topics.
Escape any string to be a valid JavaScript string literal between double quotes or single quotes.
npm install js-string-escapeIf you need to generate JavaScript output, this library will help you safely put arbitrary data in JavaScript strings:
jsStringEscape = require('js-string-escape')
console.log('"' + jsStringEscape('Quotes (\", \'), newlines (\n), etc.') + '"')
// => "Quotes (\", \'), newlines (\n), etc."In other words, given any string s, the following invariants hold:
eval('"' + jsStringEscape(s) + '"') === s
eval("'" + jsStringEscape(s) + "'") === sThese eval expressions are safe with untrusted strings s.
Non-strings will be cast to strings.
This library has been checked against ECMAScript 5.1 and tested against all Unicode code points.
Note that the returned string is not necessarily valid JSON, since JSON
disallows control characters, and \' is illegal in JSON.