Wednesday, 23 March 2011

JavaScript: special characters


JavaScript code is full of special characters. When coding, you will end up using a lot of apostrophes, quotes and so on. Let me explain it through a simple example.
<script type="text/javascript">
document.write("John said "Cheers!" while raising a glass of wine.");
As you may noticed, in the above code we have a series of quotes. The first one is defining the starting point of the string we want to output, while the last one is the ending point. Just to be more clear, the red quotes are the boundaries of the text string, while the green ones should be part of the string itself. If we use the above code, an error will be the result, because the first green quote will be interpreted as the ending of the string. That is as if the string is cut like:
John said
leaving the rest
Cheers!" while raising a glass of wine.
How to deal with that?

To avoid that issue a backslash (\) is used before special characters. That takes us to the correct syntax of the above snippet:
<script type="text/javascript">
document.write("John said \"Cheers!\" while raising a glass of wine.");
That will output the correct text:
John said "Cheers!" while raising a glass of wine

When to use the backslash
You should use the backslash when dealing with:

1) single quote ( \' )
2) double quote ( \" )
3) backslash ( \\ )
4) new line ( \n )
5) carriage return ( \r )
6) tab ( \t )
7) backspace ( \b )
8) form feed ( \f )

I have used document.write as an example. However you should use the backslash every time you deal with string and special characters. For example, if we are setting a variable with double quotes in it, we have to use the backslash.
<script type="text/javascript">
var txt = "John said \"Cheers!\" while raising a glass of wine.";

Every time we have those special characters, we have to use backslash.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.