0

While writing "\" in Chrome console I get the following error:

VM242674:1 Uncaught SyntaxError: Invalid or unexpected token

In Firefox it gives following error:

Uncaught SyntaxError: '' string literal contains an unescaped line break

while writting "\\" gives: "\\" in both browsers

What is the proper way to write "\" in JavaScript?

1
  • You can (and generally should) use single quotes to delimit a string that contains double quotes - '""' Commented Jul 7, 2021 at 16:13

2 Answers 2

1

Do not let the rendering of a string in the console, which may display strings including escape sequences and wrapped in quotes because it is a debugging tool, confuse you.

If you want a slash in a string, then escape it with a second slash.

const string = "\\";
const node = document.createTextNode(string);
document.body.appendChild(node);

Sign up to request clarification or add additional context in comments.

3 Comments

Is it a bug or it is meant to be like this?
@YadavDhakal — It's meant to be like that.
@YadavDhakal a backslash is supposed to be part of an escape sequence, e.g "\n" is a new line. So, "\" is the opening double quote of a string, followed by the escape sequence \" (which just means a " character in the string) but no closing double quote. This is interpretation tends to hold across many programming languages - Java, C#, PHP, just to name a few.
-1

"\\" is the correct way to write \

Example: console.log('This will print as a single back slash \\')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.