JSPM

js-string-escape

1.0.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 2675290
  • Score
    100M100P100Q212486F
  • License MIT

Escape strings for use as JavaScript string literals

Package Exports

  • js-string-escape

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (js-string-escape) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

js-string-escape

Build Status

Escape any string to be a valid JavaScript string literal between double quotes or single quotes.

Installation

npm install js-string-escape

Example

If 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) + "'") === s

These eval expressions are safe with untrusted strings s.

Non-strings will be cast to strings.

Compliance

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.