Using escape codes/sequence — special characters

If you have used special characters in HTML, you may already know the purpose of using special characters. Like in HTML, special characters in JavaScript represent those characters that cannot be typed from the keyboard. For example, if you wanted to display a tab character in JavaScript, you cannot simply use the tab key. You will rather use the \t escape code (also called escape sequence). The backslash ("\") in JavaScript has a special meaning because it is used with any special character you want to display in your web document. Table 1 lists the common escape sequences with the corresponding character that it represents. For instance, to display a new line, you will use the \n.

Table 1 common escape code / escape sequences in JavaScript
Escape code / escape sequences Character represented
\b backspace
\f form feed
\n new line
\r carriage return
\t tab (horizontal)
\v tab (vertical)
\' single quote
\" double quote
\\ backslash

As indicated above, the backslash has a special meaning in JavaScript. As such, how would you display a backslash in JavaScript? As table 1 shows, to display a backslash we will use \\. For instance,

<script language="javascript">
document.write ("Use \\n to start a new line.");


As another example, let's say we want to print a double quotation mark as in:

To display the double quotation marks around the word JavaScript, you can use the escape sequence \":

<script language="javascript">
document.write ("Welcome to \"JavaScript\"!");