Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Escaping JSON-stringified data for use as a JavaScript string literal
// This object contains a string value that in contains a single quote,
// a double quote, a backtick, and a backslash.
const data = { foo: `a'b"c\`d\\e` };
// Turn the data into its JSON-stringified form.
const json = JSON.stringify(data);
// Now, we want to insert the data into a script body as a JavaScript
// string literal per,
// escaping special characters like `"` in the data.
// With, the output of
// JSON.stringify is guaranteed to be syntactically valid ECMAScript,
// so let’s just use that:
const jsStringLiteral = JSON.stringify(json);
// Note: if you’re aiming to inject this script body into a <script>
// within an HTML document, you need additional escaping per
// In such cases, instead of JSON.stringify,
// consider using a specialized utility such as jsesc with
// its `isScriptContext: true` setting:
// Create the final script body.
const scriptBody = `const data = JSON.parse(${ jsStringLiteral });`;
// Log the result.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment