Escape quotes in JavaScript

'It\'s "ready"'

'It\'s "ready"' is the string It’s “ready” in JavaScript. Inside single quotes, a backslash before a single quote keeps it from ending the string, and double quotes need nothing. Inside double quotes it’s the other way round, and a template literal needs neither:

const a = 'It\'s "ready"';
const b = "It's \"ready\"";
const c = `It's "ready"`;
const d = 'It\'s \"ready\"';
console.log(a, a === b && b === c && c === d);
// It's "ready" true

All four are the same string. The last is what the tool below gives for It's "ready": it escapes both kinds of quote, so its result works between either. Leave the backslash out and the string ends early:

const s = 'It's "ready"';
// SyntaxError: Unexpected identifier 's'

Template literals

Backticks take both quotes as they are, but a backtick or a ${ inside needs a backslash. String.raw keeps every backslash as written, which suits Windows paths:

const name = 'Ann';
console.log(`Use \` and \${name}, not ${name}`);
console.log(String.raw`C:\temp\new`);
// Use ` and ${name}, not Ann
// C:\temp\new

\u and \x escapes

Any character can be written by its code: \u0027 is ', \x22 is ", and \u{1F986} is 🦆, the same as the surrogate pair \uD83E\uDD86. The tool’s Unescape reads all of these: It\u0027s \x22ready\x22 \u{1F986} comes back as It's "ready" 🦆.

Octal escapes such as \047 are a legacy form. Node prints ' for '\047' in a script, but strict-mode code, which includes every ES module, throws SyntaxError: Octal escape sequences are not allowed in strict mode, and template literals reject them too.

Building JavaScript source

When a program writes a string into generated JavaScript, let JSON.stringify make the literal. It escapes ", \ and line breaks, and since ES2019 every JSON string is also valid JavaScript:

const text = 'It\'s "ready"\n</script>';
const code = `const message = ${JSON.stringify(text)};`;
console.log(code);
// const message = "It's \"ready\"\n</script>";

Evaluating that line gives back the same text. Inside an HTML <script> element, though, the </script> in the string still ends the script, because the HTML parser knows nothing about JavaScript strings. Write < as \u003c and the string means the same:

JSON.stringify(text).replaceAll('<', '\\u003c');
// "It's \"ready\"\n\u003c/script>"

The reverse doesn’t hold: \' is JavaScript, not JSON, and JSON.parse('"It\\\'s"') throws Bad escaped character in JSON at position 4.

Try it in the String Escape & Unescape

12 of up to 100,000 characters

JSON's rules, plus \' for single quotes.

Result
It\'s \"ready\"

Runs in your browser. Nothing you enter is sent anywhere.