You don't have to escape either of them, unless you want to use the contents of the template literal as a string literal quoted with a single quote at some point. Which looks really suspect: Never manually create JSON strings (and if you do, don't do it wrapped in a string literal in a template literal! :-) ). But if you're looking to define that string literal within the template literal here's how to do the escaping at the string literal level:
To escape the '
in It's
in the string literal the template will define, you need to put a backslash in front of it. But because backslashes are escapes in template literals, you need to escape the backslash so it's not consumed by the template literal and later is used when evaluating the string literal. So:
// Define the template literal:
const s1 = `'{"0": "It\\'s Friday today"}'`;
// Escaped backslash −^^
console.log(s1);
// Evaluate the single-quoted string literal it defined:
const s2 = eval("(" + s1 + ")");
console.log(s2);
// Since that defined a string containing JSON, let's parse it:
const obj = JSON.parse(s2);
console.log(obj[0]);
In the second example with the \n
, that \n
escape sequence is being consumed at the template literal level, meaning the template literal contains a newline. But you want it not to be a newline from the template literal's perspective, so you...escape it: \\n
. Now it's not a newline to the template literal anymore, but it is to the single-quoted string literal. Now it's the same as It's
above: If you don't want the single-quoted string literal to consume the \n
esape sequence, you need to escape it. That means you end up with \\\\n
:
// Define the template literal:
// 1st escaped backslash −−−vv
const s1 = `'{"0": "Thursday\\\\nFriday"}'`;
// 2nd escaped backslash −−−−−^^
console.log(s1);
// Evaluate the single-quoted string literal it defined:
const s2 = eval("(" + s1 + ")");
console.log(s2);
// Since that defined a string containing JSON, let's parse it:
const obj = JSON.parse(s2);
console.log(obj[0]);