Just about every programming language has a list of special characters. These are characters that have a special purpose. JavaScript is no different. In JavaScript, you can add special characters to a text string by prefixing the string with the backslash character.
In the following example, we will see how the use of special characters are needed to properly display a message.
var txt="Did you read that really "cool" book?";
document.write(txt);
In JavaScript single or double quotes are used to store the value of a string. Since we placed quotes around the word cool, the full string value is not assigned to the variable.
If we require the quotes in our output, we need to use special characters in our code. Here is how we would address that need.
var txt="Did you read that really \"cool\" book?";
document.write(txt);
The following is a list of the most common special characters that you will be using when working with JavaScript code. Aside from the single and double quotes, the new line special character is also very common.
Code | Output |
---|---|
\' | Single quote |
\" | Double quote |
\\ | Backslash |
\b | Backspace |
\f | Form feed |
\n | New line |
\r | Carriage return |
\t | Tab |
\v | Vertical tab |