How to Use Backslash to Escape Quotation Marks in JavaScript: Preventing it From Becoming a String

Sometimes you’re going to want to do something in between quotes but you don’t want it to turn into a string with all the rest.

What you want to do is use the backslash (\) along with a special character designated in JavaScript to perform a certain task.

This is what’s called escaping the character.

Take for example below:

console.log("We're going to put this line on top\nand this line below by using the Newlines escape");

We would get this:

We're going to put this line on top
and this line below by using the Newlines escape

What if you want to have a backslash inside a quoted string?

Let’s say for some weird reason, you want to have the actual backslash (\) show up within your string that is surrounded by quotation marks.

You don’t want it to turn into an escape.

You wanted to look like this output:

"There is a backslash in \ the middle of this sentence"

Well, it turns out that if you put two backsplashes together, they will join forces and become one visible backslash within a quoted string.

So this is how you write code that will reveal a backslash exactly like the one above:

console.log("There is a backslash in \\ the middle of this sentence");

Do you see the double backslash here? Doing a double backslash here will basically show up exactly like what I showed in the output above.

How to read backslashes in JavaScript

Here’s a quick quiz.

Example 1: Lots of backslashes

What does the output here look like when it’s run through your code editor?

console.log("this one is really \\\n\"\\n\" complicated, just give up")

It looks like this:

this one is really \
"\n" complicated, just give up

OMG looks terrible huh?

Let’s analyze this.

We know that JavaScript reads these things from left to right. so if we’re going by that method, the first thing we’ll see is the first two backslashes (\\).

Remember what I said before? Two backslashes make a single visible backslash (\).

After that, we see a single backslash followed by the letter n (\n). We know the letter n is in front of a backslash and turns into a Newline. So, we should expect the sentence to split now.

Now, we can see yet another double backslash (\\) in front of that. Again, that turns into a single backslash (\).

Moving forward, we’re now coming across another n (this time) by itself. Technically, there’s no escape backslash behind it. I mean, there is one (the visible one that was just created from the double backslashes) but it’s already been translated into a string so it has no more escaping power. It’s just an inert string now. This time, we can’t do anything with it. We’ll just leave it alone and let it output as it is.

Finally, the final backslash followed by a double quote translates into simply a double quote by itself!

We’re done! Easy peasy.

Leave a Comment