1 2 3 4 5 6 7 8 9 10
const str = 'This is a \'quoted\' string.'; // Using single quotes within single quotes console.log(str); // Output: This is a 'quoted' string. const str2 = "This is a \"quoted\" string."; // Using double quotes within double quotes console.log(str2); // Output: This is a "quoted" string. const str3 = 'This is a \nnew line.'; // Using a newline character console.log(str3); // Output: This is a // new line.
2. Using the backslash as an escape character: The backslash itself can be escaped by using two consecutive backslashes (\\). This is useful when you need to include a literal backslash in your string.
1 2 3
const str = 'This is a backslash: \\'; console.log(str); // Output: This is a backslash: \
3. Using the String.fromCharCode() method: The
String.fromCharCode() method can be used to escape special characters by their Unicode representation. By providing the Unicode value of a character, you can create a string with the escaped character.
1 2 3
const str = String.fromCharCode(65, 66, 67); // Escaping characters with Unicode values console.log(str); // Output: ABC
4. Using template literals (backticks): Template literals, denoted by backticks (
), allow you to include special characters without explicit escaping. However, if you want to include a backtick itself within a template literal, you can escape it with a backslash.
1 2 3
const str = `This is a template literal with \`backticks\`.`; console.log(str); // Output: This is a template literal with `backticks`.