js-string-escape
js-string-escape is a tiny CommonJS utility for putting arbitrary text inside a classic single-quoted or double-quoted JavaScript string literal. It returns only the escaped contents, not the surrounding quote marks. Its single function escapes both quote characters, backslashes, newlines, carriage returns, and the Unicode line and paragraph separators, while coercing non-string inputs with normal JavaScript string conversion. It is a source-code generation helper, not a JSON serializer, HTML escaper, template-literal escaper, or general security sanitizer.
Correct and dependency-free for one old-fashioned job: embedding text in classic JavaScript string literals. For new code, use JSON.stringify for data, jsesc for configurable escaping, or a real code generator for full programs; do not install this for template literals or inline scripts.
Use it if
- You maintain a CommonJS code generator that needs to insert text into classic single-quoted or double-quoted JavaScript literals
- You need the same fixed escaping behavior for either quote style, including U+2028 and U+2029 line terminators
- You already depend on this package and only need its exact one-function contract, with no configuration or runtime dependencies
- You must support a very old Node codebase where the package's declared Node 0.8 minimum still matters
- You are producing JSON: the README explicitly says its output is not necessarily valid JSON because control characters can remain literal and backslash-single-quote is illegal in JSON; use JSON.stringify instead
- You put data inside an inline HTML script: the implementation does not escape less-than signs or a closing script tag, so the HTML parser can end the script before JavaScript sees the quoted value
- You generate template literals: backticks and ${...} are not escaped, and template-literal support has remained an open issue since 2018
- You want first-party TypeScript or native ESM support: version 1.0.1 exposes one CommonJS entry point with no bundled declaration file; types come from a separate @types package
- You require active maintenance or configurable output: the latest release and latest default-branch commit are from March 2016, while requests for quote-selection and template support remain open
Setup reality
Installation is only npm install js-string-escape. Version 1.0.1 has no runtime dependencies, native extension, peer dependency, credential, environment variable, or config file. The first surprise is the return shape: calling the function gives you the inside of a JavaScript string literal, so your generator must add matching single or double quotes. It always escapes both quote styles and offers no option to choose one. The second surprise is scope. Newline, carriage return, U+2028, and U+2029 are handled, but backticks, dollar-brace interpolation, less-than signs, HTML closing tags, and ordinary control characters are not transformed. That is correct for its promised ES5.1 single- and double-quoted literal use, but wrong for template literals, JSON, or inline HTML scripts. Non-strings are accepted by coercion, so an object silently becomes [object Object] rather than serialized data. The package is CommonJS-only. Node ESM can load it through createRequire or default CommonJS interop, but there is no exports map or ESM build. TypeScript users need the separately maintained @types/js-string-escape package and its export-equals import shape. The npm metadata still declares Node >=0.8, which describes compatibility rather than current maintenance; the published tests use an old Tap generation and the repository's visible commit history stops in 2016.
Patterns
Generate a double-quoted JavaScript literaldouble-quoted-literal
const escape = require('js-string-escape')
const input = 'She said "hello"'
const literal = '"' + escape(input) + '"'
// => "She said \"hello\""The function returns only escaped contents. Your generator must add the opening and closing quote characters.
Generate a single-quoted JavaScript literalsingle-quoted-literal
const escape = require('js-string-escape')
const input = "Ada's notes"
const literal = "'" + escape(input) + "'"
// => 'Ada\'s notes'Both single and double quotes are always escaped, so the returned contents work inside either classic quote style.
Keep line breaks inside generated sourceescape-line-breaks
const escape = require('js-string-escape')
const input = 'first line\nsecond line\rthird line'
const source = 'const message = "' + escape(input) + '";'
// source contains \n and \r escape sequencesLiteral LF and CR characters would terminate or invalidate old-style source literals; the package converts them to backslash escapes.
Escape Unicode line and paragraph separatorsescape-unicode-separators
const escape = require('js-string-escape')
const input = 'left\u2028middle\u2029right'
const escaped = escape(input)
// => left\u2028middle\u2029rightU+2028 and U+2029 are part of the implementation's four handled line terminators and are emitted as explicit Unicode escapes.
Understand non-string coercioncoerce-non-strings
const escape = require('js-string-escape')
escape(null) // 'null'
escape(false) // 'false'
escape({ id: 42 }) // '[object Object]'Inputs are converted with ordinary string coercion. Use JSON.stringify when an object must retain its structure.
Generate an array of JavaScript string literalsgenerate-string-array
const escape = require('js-string-escape')
const names = ["Ada's file", 'line one\nline two']
const source = '["' + names.map(escape).join('", "') + '"]'
// => ["Ada\'s file", "line one\nline two"]This is suitable only when every element is meant to become a string. Use JSON.stringify for mixed arrays or structured values.
Write a generated CommonJS modulewrite-commonjs-module
const fs = require('node:fs')
const escape = require('js-string-escape')
const banner = 'Build "green"\nReady'
const source = 'module.exports = "' + escape(banner) + '"\n'
fs.writeFileSync('generated-message.cjs', source, 'utf8')This is the package's best fit: trusted source scaffolding with one arbitrary string value inserted into a classic quoted literal.
Load the CommonJS package from Node ESMload-from-esm
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const escape = require('js-string-escape')
const literal = '"' + escape('ESM caller') + '"'Version 1.0.1 has no module field or exports map. createRequire makes the CommonJS boundary explicit in an ESM project.
Use the separate TypeScript declarationsuse-with-typescript
// npm install js-string-escape
// npm install --save-dev @types/js-string-escape
import escape = require('js-string-escape')
const contents: string = escape('typed input')The runtime package ships no declarations. @types/js-string-escape declares an export-equals function accepting any input.
Use JSON.stringify for JSON outputencode-json-instead
const value = { message: "Ada's note\nnext line" }
const json = JSON.stringify(value)
JSON.parse(json) // round-trips the objectDo not substitute js-string-escape here. Its README warns that the returned contents can be invalid JSON.
Avoid it for data inside inline HTML scriptsembed-inline-script-data
const data = { value: '</script><script>alert(1)</script>' }
const safeJson = JSON.stringify(data).replace(/</g, '\\u003c')
const html = `<script type="application/json" id="payload">${safeJson}</script>`js-string-escape leaves less-than signs unchanged. In HTML, a closing script tag is recognized before the JavaScript parser processes quotes.
Do not insert its output into a template literalavoid-template-literals
const escape = require('js-string-escape')
const input = '`; runSomething(); // ${alsoRuns()}'
// Safe target for this package: classic quotes
const source = 'const value = "' + escape(input) + '";'Backticks and dollar-brace interpolation are untouched. Template-literal support is an open repository issue, so use classic quotes or another escaper.
Alternatives
| Package | Registry | Pick it when |
|---|---|---|
| jsesc | npm | You need configurable JavaScript or JSON escaping, ASCII-safe output, quote selection, or escape-everything modes |
| serialize-javascript | npm | You need to serialize whole values such as objects, regular expressions, or functions instead of only string contents |
| escodegen | npm | You are generating complete JavaScript programs from an AST and want a code generator to own literal quoting and syntax |