JavaScript escape sequences

employing special workarounds for special cases of strings

// updated 2025-05-11 11:42

Sometimes, we have a certain character (such as an apostrophe or quotation marks) in our string that will result in the JavaScript code not working! These include:

  • quotation marks
  • line breaks
  • tab indents

Fortunately, escape sequences exist as special workarounds!

Escaping quotation marks ( \ )

We can escape quotation marks with a backslash before each quotation mark:

1let narration = "Then he yelled \"Let there be quotation marks!\"
2console.log(narration)
3
4/* output:
5Then he yelled "Let there be quotation marks!"
6*/
7
8let singleQuotes = 'Yes, these are \'scare quotes\'!'
9console.log(singleQuotes)
10
11/* output:
12Yes, these are 'scare quotes'!

As in the above, we can escape single quotes or double quotes with the same escape sequence!

Escaping line breaks ( \n )

We can insert the escape sequence \n where we want a line break to occur (rather than just using the "return" key):

1let hours = "Business hours \nMonday-Friday 9-5 \nSaturday 12-6 \nSunday 12-5"
2console.log(hours)
3
4/* output:
5Business hours
6Monday-Friday 9-5
7Saturday 12-6
8Sunday 12-5 */

Escaping tab indents ( \t )

Similar to \n for line breaks, we use \t for tab indents (4 character spaces):

1let tabbed = "Something \n\ttabbed"
2console.log(tabbed)
3
4/* output: 
5Something
6    tabbed
7*/

⬅️ older (in textbook-javascript)
📒 JavaScript data fetching
newer (in textbook-javascript) ➡️
JavaScript string interpolation 📒
⬅️ older (in code)
📒 JavaScript data fetching
newer (in code) ➡️
JavaScript string interpolation 📒
⬅️ older (posts)
📒 JavaScript data fetching
newer (posts) ➡️
JavaScript string interpolation 📒