Monday, July 14, 2014

JavaScript Escape Characters

In JavaScript, strings are written as characters inside single or double quotes. Hence, you cannot make a string have quotes inside of it or do other functions.. because it is simply a string and won't recognize it as a function. So, if you are doing something inside of quotes, you have to use these backslashes to make escape characters. These characters will "escape" the rules of the string!

For example, JS will see this string:

"Hello my name is "Crystal Tenn.""
.. as "Hello my name is "

You can use escape characters by putting a backslash before the quotes.

"Hello my name is \"Crystal Tenn.\""
And, this will print what we wanted: "Hello my name is "Crystal Tenn.""

Another example in shell I like is the following:
This is a common way to delete all files in the current directory:

rm *    


This is how to delete a particular file called *.

rm \*   

The following is a list of escape characters in JS:

  • \' single quote
  • \" double quote
  • \\ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab
  • \0 null character