js escape quotes code example

Example 1: javascript escape quote method

stringToEscape.replace(/"/g, '\\\"')

Example 2: javascript escape single quote

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";

Example 3: javascript var in quotes

const poem = "The Wide Ocean";
const author = "Pablo Neruda";

const favePoem = `My favorite poem is ${poem} by ${author}.`;

Example 4: javascript escape single quote

var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
//           ^         ^ same types, hence we need to escape it with a backslash

Example 5: javascript var in quotes

var myArray = [123, 15, 187, 32];

myArray.forEach(function (value, i) {
    console.log('%d: %s', i, value);
});

// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32