30 Days Of JavaScript

Day 14: Strings and JSON

Lesson 1: String escape sequences

This is a string

1let name = "All The Code";

A series of characters between a pair of ", ' or ` is a string.

But what if you want to use any of those quotation marks in a string?

1let str = "All The Code says: "Hello World" loudly";

JavaScript is going to get very confused about this, it will think it is two strings with some invalid code in between.

It will read this as let name = "All The Code says: " then Hello World then " loudly"

To put Hello World in speech marks we have two options. The first (and most traditionally correct way) is to "escape" the speech marks that we don't want JavaScript to get confused about. To do this we use a \ to tell JavaScript "Turn the next special character into a string character".

So we would write this

The other way is to simply use the quotation mark you didn't use to start the string:

And if you simply must use the double quotes for the Hello World you would swap them around and do this: let str = 'All The Code says: "Hello World" loudly'.

I think this is better however some people don't like it so I'm showing you both ways.

There are a number of escape characters in JavaScript, they are as follows:

  • \b - Backspace
  • \f - Form feed
  • \n - New line
  • \r - Carriage return
  • \t - Horizontal tab
  • \v - Vertical tab

None of these will work in the playground sadly, due to the crazy shenanigans I've had to pull to get it to work in the first place. The most common to use are \n and \t for new line and tab.

This does raise an interesting question though. What do you do if you want to print a \?

Well, you can probably guess, we have to escape it!

So to print a \ in a string we have to do \\ which is basically saying, escape the escape character to it prints as a back slash.

Try removing one of the back slashes and see what you get.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co