JavaScript escape characters | Show escape characters in a string uses the \ (backslash)

JavaScript uses the \ (backslash) as an escape characters 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 characters.

<!DOCTYPE html>
<html>
<body>

  <script>
    str = "Hello \\n World";
   console.log(str);

 </script>
</body>
</html>

Output:

Another example escaping double quotes 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 and 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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.