As you may noticed, in the above code we have a series of quotes. The first one is defining the starting point of the string we want to output, while the last one is the ending point. Just to be more clear, the red quotes are the boundaries of the text string, while the green ones should be part of the string itself. If we use the above code, an error will be the result, because the first green quote will be interpreted as the ending of the string. That is as if the string is cut like:
document.write("John said "Cheers!" while raising a glass of wine.");
John saidleaving the rest
Cheers!" while raising a glass of wine.out.
How to deal with that?
BackslashTo avoid that issue a backslash (\) is used before special characters. That takes us to the correct syntax of the above snippet:
That will output the correct text:
document.write("John said \"Cheers!\" while raising a glass of wine.");
John said "Cheers!" while raising a glass of wine
When to use the backslashYou should use the backslash when dealing with:
1) single quote ( \' )
2) double quote ( \" )
3) backslash ( \\ )
4) new line ( \n )
5) carriage return ( \r )
6) tab ( \t )
7) backspace ( \b )
8) form feed ( \f )
NotesI have used document.write as an example. However you should use the backslash every time you deal with string and special characters. For example, if we are setting a variable with double quotes in it, we have to use the backslash.
var txt = "John said \"Cheers!\" while raising a glass of wine.";
Every time we have those special characters, we have to use backslash.