Special Characters


© Muhammad Ali Shah


Skill Level: Intermediate
Skills Required: Basic JavaScript


Abstract:

This week's rather short article discusses use of special characters in JavaScript. Most of the JavaScript syntax is similar to C/C++ and Java. However, this stuff is equally easy for non-programmers to master.


Special Characters:

In HTML, we can display special characters as < by writing &lt;. We have to do this because the < sign has some pre-defined meaning in HTML. Similarly, in JavaScript a few things have pre-defined meanings; the quotation mark "show strings" is an example.

So how do we write a string, say in an alert box, which contains quotation marks. More specifically, can we write the following?

alert ("He said, "I am OK!"");

As you might have guessed, this syntax is incorrect.


The Backslash:

For our rescue we have the backslash \. To distinguish a quotation mark that encloses a string from one that is part of the text, we preceede the later with \. The following syntax is correct:

alert ("He said, \"I am OK!\"");

Other important special characters are outlined in the following table:


Special Character Used for
\n Line feed / New line
\t Tab character
\" Quotation Marks


An Example:

The following rather simple example demonstrates the most commonly used special characters.

<html>
<head>
<title>Special Characters</title>

<script language="JavaScript">
function show()
{
   var str;
   str="This is my first line.\n";
   str+="This continues in the next line \t but with a tag."
   alert (str);
   alert ("He said, \"I am OK\"");
}
</script>
</head>

<body onLoad="show()">
</body>
</html>



Last Words:

We have seen that backslash character can be useful in representing special characters, but how do we write a backslash? The answer is very simple: write "\\" (double backslash) when you want to write "\" on screen. Questions, comments and suggestions can be posted in discussions area.

Go To Page: 1


The copyright of the article Special Characters in JavaScript is owned by . Permission to republish Special Characters in print or online must be granted by the author in writing.

Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo