JavaScript uses the \ (backslash) as an escape character for:
- \’ single quote
- \” double quote
- \ backslash
- \n newline
- \r carriage return
- \t tab
- \b backspace
- \f form feed
- \v vertical tab (IE < 9 treats ‘\v’ as ‘v’ instead of a vertical tab (‘\x0B’). If cross-browser compatibility is a concern, use \x0B instead of \v.)
- \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence).
Note: that the \v and \0 escapes are not allowed in JSON strings.
Examples escape characters in JavaScript
HTML example code.
How can I show escape characters when printing in JavaScript?
Example:
str = "Hello\nWorld";
console.log(str);
Gives:
Hello
World
When we want it to give:
Hello\nWorld
Solution: use the \ (backslash) as an escape character.
<!DOCTYPE html>
<html>
<body>
<script>
str = "Hello \\n World";
console.log(str);
</script>
</body>
</html>
Output:
Another example of escaping double quotes is special char
<script>
var str = "They call it an \\n \"escape\" character";
console.log(str);
</script>
Output: They call it an \n “escape” character
Do comment if you have any doubts or suggestions on this is JS char tutorial.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version