How do I escape special characters in a string in JavaScript?
Antek N
antek n profile pic

In JavaScript, there are a few ways to escape special characters within a string. Escaping characters is necessary when you want to include characters that have special meanings or when you want to represent characters that are not easily typed or displayed. 1. Using backslashes to escape characters: You can use backslashes (\) to escape special characters within a string. When you precede a special character with a backslash, it is treated as a literal character rather than having its usual meaning.

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: TheString.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`.

These are some of the commonly used methods for escaping special characters in JavaScript strings. Choose the appropriate approach based on your requirements and the specific characters you need to escape.