JavaScript Tutorial Part I- Some Basics
By Will Bontrager2004-02-09
Using strings of characters
Strings of characters need to be enclosed between either apostrophes (') or quote marks (").
Whichever character you choose, it must be used both at the beginning and at the end of the string.
If you have one or more apostrophes within your string, it makes good sense to choose quote marks to contain the string. Example:
"I'm hot."
On the other hand, if you have one or more quote marks within your string, it makes sense to enclose it within apostrophes, like this:
'He said, "hot".'
A special situation arises when you have a string with both an apostrophe and a quote mark within it. In that case, you put a backslash character in front of each occurrence of the character that encloses the string. For example, the string of characters
He said, "I'm hot."
can be enclosed within apostrophes as
'He said, "I\'m hot."'
or within quote marks as
"He said, \"I'm hot.\""
The backslash tells the browser's interpreter to treat the character following the backslash as a literal character rather than an "end of string" marker. Once the interpreter has done that, it discards the backslash from the string.
(If you want to use a backslash in a string, you must use two of them in sequence -- the browser will discard the first one.)
Try this JavaScript program code in a web page to see it work:
<script language="JavaScript">
<!--
var hotstuff = 'He said, "I\'m hot."';
document.write(hotstuff);
// -->
</script>
Tutorial Pages:
» JavaScript Tutorial Part I- Some Basics
» Orientation
» How the browser knows it is JavaScript
» This is how JavaScript works
» Some programming basics
» How to make your program remember things
» Here it is, all put together
» Using strings of characters
» To come
Copyright 2004 Bontrager Connection, LLC
