Special Characters© Muhammad Ali Shah
Sep 26, 2000
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 <. 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. |