Java Script Include a Backslash Character in a String
By Stephen Bucaro
In Java Script strings, escape sequences are used to inform the
interpreter that a character is not just a letter, but that special action
should be taken. For example the escape sequence \n indicates that
the string should continue on a new line. A backslash indicates the next
character is part of an escape sequence.
But what if you actually want to include a backslash in a string, not to start
an escape sequence, but to just be displayed as a backslash? To print an actual
backslash, you have to escape the backslash with a backslash, as shown below.
var aStr = "To include a backslash in a string, escape it with a \\";
In this case, the backslash would be displayed because it's actually part of
an instruction to the interpreter to display a backslash.
In the example below, the programmer's intent was to display a message
informing the user that the file was copied to the \networking folder.
alert("File copied to the \networking folder");
Instead, it informs the user that the file was copied to the etworking
folder. Where the heck is the etworking folder? The error is caused
because the \n in \networking is interpreted as an escape
character instructing the interpreter to continue on a new line.
In the example below, the backslash was properly escaped.
alert("File copied to the \\networking folder");
More Java Script Code:
• The while Loop
• The Location Object
• The Document Object Model (DOM)
• Access Web Page Elements With getElementById
• Generating Random Numbers
• Java Script Data Types
• Determine Absolute Value
• Extract Part of a String
• Cookie Power Made Easy
• Java Script Number Object