jsesc

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

jsesc Build status Code coverage status Dependency 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 

Related Repositories

wrap-ansi

wrap-ansi

Wordwrap a string with ANSI escape codes ...

mocha-unfunk-reporter

mocha-unfunk-reporter

Mocha reporter without console funkyness ...