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