3 Backslash Uses in JavaScript Strings
The skilled JavaScript programmer knows these 3 uses for the backslash character by heart. No need to think. The fingers type the backslash character seemingly automatically in response to the need.
Use 1: Escaping the string delimiter.
JavaScript strings are delimited by either a double- or single-quotation mark. (Either the " or ' character.)
Example:
"Hello, World!"
So how does one use the delimiter character within the string itself? By escaping it with a backslash character.
Example:
"The name is \"Mr. Howdy\""
Use 2: Inserting line feed characters.
In alert messages (for example) line feeds may be desirable to break a line or to insert a blank line. This is done with the
Example:
"one\ntwo\n\neleven\ntwelve"
The above prints the message as:
one
two
eleven
twelve
\n inserts a line break. \n\n inserts two line breaks, resulting in a blank line.
Use 3: Assigning multi-line strings.
Assigning a string value to a JavaScript variable is generally required to be all one line. A backslash character at the end of the line, however, continues the string on the next line.
Example:
"Row, row, row your boat.\
Gently down the stream."
This article's 3 uses for the backslash character will come in handy time and again as you write JavaScript code.
Here is a function that demonstrates each of the 3 uses:
<script type="text/javascript"> function displayMessage() { message = "When it rained, I decided to \ read the \"All Things Technical\" book, \ instead of going to the park.\n\nThen the \ sun came out and I unchanged my mind."; alert(message); } </script>
Function displayMessage() is live as an example in this article. Click here to run function displayMessage().
Will Bontrager