JavaScript » Operators » Backslash Escaping

The \ (backslash) is used to insert apostrophes, carriage returns, quotes, tabs, and other special characters inside a string.

For example, in JavaScript, the start and stop of a string is delimited with either single or double quotes. However, if the string contains single and/or double quotes, you have problems.

Consider the string, "My favorite rose is the "Peach Delight.""

JavasScript will chop the output to, My favorite rose is the

Fortunately, this has a very simple solution. All you have to do is to place a backslash \ before each double quote in "Peach Delight". This turns each \" into a string literal.

The string is becomes, "My favorite rose is the \"Peach Delight\"."

JavasScript will now output, My favorite rose is the "Peach Delight".

This same concept is used with a variety of other characters. These backslash pairs are refered to as inline or escaped characters:

Code: Outputs:
\'single quote
\" double quote
\\ backslash
\b backspace
\f form feed
\n new line
\r carriage return
\t tab