Special Characters and Escaping Characters in JavaScript

Special characters in JavaScript

Special characters allow you to add to your string things that otherwise you could not.

Example:

document.write("The following folder C:\MyDocuments");
document.write("The following folder C:\\MyDocuments");

The first document.write() method will not print the backslash after C: but the second document.write() method will. That is because in order to output a backslash (\) you have to use in your code a special code which in our case is double backslash (\\). You can see the list of JavaScript special characters below.

Output characterSpecial code used
Backslash (\)\\
Double quotes (“)\”
Single quote (‘)\’
Backspace\b
Form feed\f
Newline\n
Carriage return\r
Tab\t
Vertical tab\v

If you want the output of your code to be viewed on two lines then you have to use the <br> in your code. The \n is just a new line in JavaScript not in the browser output.

Escaping characters

You can escape certain characters in JavaScript so they can show up correctly in the browser. Let’s say that you want the output from a document.write() command to be “He said, “I am a web developer.””

document.write("He said, "I am a web developer."");

The above command will cause problems in the browser. The first double quotes will make sense for the browser but when it gets to the second double quotes it thinks the string is closed now and expects the ending parenthesis and semicolon. Instead, it finds more text!

Placing a backslash in front of the quotes you want to escape tells the browser that the quotes are part of the sting avoiding errors.

document.write("He said, \"I am a web developer.\"");

In the above example, “I am a web developer.”, if single quotes would be used, then escaping them would not be necessary. Single quotes (instead of double) can be use to enclose the string but the important thing to remember is that you have to use different types of quotation marks inside the string as you use to enclose the string. If it is needed to go one level (or more) deeper with quotation marks then you have to start escaping them.

Leave a Reply