Skip to Content

Advertisement

You (Level 0)
0% Complete
Last Badge Earned
None

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

I've attached my favorite JavaScript and jQuery book. I would encourage you to read it as well.

Your code will execute in this window.



Let's explore some more tutorials or topics!

Next Tutorial Previous Tutorial

Advertisement

If you enjoyed this resource, support me by sharing this page with others.

Comment on

Show Comments

No comments yet... Be the first!



Advertisement