mrkeyoor.com_
Sat 08 Aug 22:51 UTC
npmUtilsupdated 08 Aug 2026

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.

Verdict

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.

API stability5/5The entire public API is one function that coerces its argument to a string and returns escaped contents, and the README documents the same contract with round-trip invariants for both quote styles. The changelog says 1.0.0 made no behavior change and merely declared the package stable; 1.0.1 only reduced the published file set. That extreme narrowness has prevented churn, though it also means feature requests stay outside the API.
Docs2/5The short README does explain installation, the missing surrounding quotes, non-string coercion, the single- and double-quote round-trip property, full Unicode testing, and the important warning that output is not JSON. It does not document the exact replacement list, CommonJS and TypeScript usage, template-literal limits, or the inline-script closing-tag risk. Its Travis badge and ES5.1 framing also reflect the project's age.
Maintenance1/5npm 1.0.1 was published on March 11, 2016, and the newest commits on the default branch are from that same release. The repository is not archived, but two real issues remain open: quote-selection support requested in 2016 and ES6 template-literal support requested in 2018. A GitHub push timestamp in 2023 does not correspond to a newer default-branch code commit or npm release, so consumers should plan as if behavior is frozen.
Ecosystem3/5The package recorded 3,054,794 npm downloads for July 31 through August 6, 2026, showing substantial continued use, most plausibly through existing dependency trees. Its public footprint is otherwise small at 73 GitHub stars, one CommonJS entry point, and no runtime dependencies. TypeScript definitions exist as the separate @types/js-string-escape 1.0.3 package, but there is no first-party ESM build, plugin system, or configurable extension surface.

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
Skip it if

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 sequences

Literal 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\u2029right

U+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 object

Do 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

PackageRegistryPick it when
jsescnpmYou need configurable JavaScript or JSON escaping, ASCII-safe output, quote selection, or escape-everything modes
serialize-javascriptnpmYou need to serialize whole values such as objects, regular expressions, or functions instead of only string contents
escodegennpmYou are generating complete JavaScript programs from an AST and want a code generator to own literal quoting and syntax