Backslash Characters
Using Escape Characters in JavaScript
If you haven’t noticed so far, I have yet to use a word that requires quotes when setting a string variable. If you put a quote while setting a string in JavaScript, you will confuse the browser. To avoid doing this, use the escape character in your code.
Example
var stringWithQuotes = "The phrase "this food is to die for" seems like it lacks logic."; document.write(stringWithQuotes);
When we run this, you will notice a nice little error. The quotation mark before this
is actually ending that string. Your browser is freaking out because it doesn’t know what to do with the following this food is to die for” seems like it lacks logic.”
when it just expected a ;
, which is the actual error.
Correcting the Error
Now, we will make JavaScript do what we want.
var stringWithQuotes = "The phrase \\"this food is to die for\\" seems like it lacks logic."; document.write(stringWithQuotes);
Result
The phrase "this food is to die for"
seems like it lacks logic.
The phrase \\"this food is to die for\\"
seems like it lacks logic.
Welcome to the Power of Escape Characters
As you can see, adding a backslash solved our problem. The escape character doesn’t stop being awesome with just quotation marks.
\'
– escapes a single quote\"
– escapes a double quote\\
– escapes a backslash\n
– creates a new line