How to escape string value in Javascript
Description
To input non-inputable value we have to use escapes.
The escapes start with a \
.
Escape | Meanings |
---|---|
\n | New line |
\t | Tab |
\b | Backspace |
\r | Carriage return |
\f | Form feed |
\\ | Backslash (\) |
\' | Escape single quote (') |
\" | Escape double quote (") |
\xnn | A character represented by hexadecimal code nn. |
\unnnn | A Unicode character represented by the hexadecimal code nnnn. |
These character literals can be included anywhere with a string and will be interpreted as if they were a single character.
var text = "This is the letter sigma: \u03a3.";
The string in the code above is 28 characters long even though the escape sequence is 6 characters long. The entire escape sequence represents a single character, so it is counted as 1.
Example
The following code uses the escape sequence to input string values.
console.log("\"");
console.log('\'');
console.log('\x42');
console.log("\u03a3");
The code above generates the following result.