Home » Tutorials » JavaScript » Backslash Characters

Backslash Characters

If you haven’t notice so far, I have yet to use a word that requires quotes when I am setting a string variable. If you put a quote while setting a string in JavaScript, you will confuse the browser. To avoid doing this, use the escape character in your code.

Example
var stringWithQuotes = "The phrase "this food is to die for" seems like it lacks logic.";
document.write(stringWithQuotes);

When we run this, you will notice a nice little error. The quotation mark before this is actually ending that string. Your browser is freaking out because it doesn’t know what to do with the following this food is to die for” seems like it lacks logic.” when it just expected a ; , which is the actual error.

Now, we will make JavaScript do what we want.

Example
var stringWithQuotes = "The phrase \"this food is to die for\" seems like it lacks logic.";
document.write(stringWithQuotes);
Result
The phrase \”this food is to die for\” seems like it lacks logic.

Welcome to the power of the escape character. As you can see, adding a solved our problem. The escape character doesn’t stop being awesome with just quotation marks.

  • \’ – escapes a single quote
  • \” – escapes a double quote
  • \\ – escapes a backslash
  • \n – creates a new line


Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Backslash Characters". After Hours Programming. Accessed on March 16, 2024. https://www.afterhoursprogramming.com/tutorial/javascript/backslash-characters/.

  • Stewart, Suzy. "Backslash Characters". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/javascript/backslash-characters/. Accessed 16 March, 2024.

  • Stewart, Suzy. Backslash Characters. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/javascript/backslash-characters/.



Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.