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:

let narration = "Then he yelled \"Let there be quotation marks!\"
console.log(narration)

/* output:
Then he yelled "Let there be quotation marks!"
*/

let singleQuotes = 'Yes, these are \'scare quotes\'!'
console.log(singleQuotes)

/* output:
Yes, 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):

let hours = "Business hours \nMonday-Friday 9-5 \nSaturday 12-6 \nSunday 12-5"
console.log(hours)

/* output:
Business hours
Monday-Friday 9-5
Saturday 12-6
Sunday 12-5 */

Escaping tab indents ( \t )

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

let tabbed = "Something \n\ttabbed"
console.log(tabbed)

/* output: 
Something
    tabbed
*/

⬅️ 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 📒