HTML and CSS Reference
In-Depth Information
FORMAT
var string_name = "string of text";
var string_name = new String("string of text");
EXAMPLE
var title="JavaScript by Example";
var title=new String("JavaScript by Example");
EXAMPLE
9.23
<html>
<head><title>The String Object</title></head>
<body bgcolor="pink">
<font face="arial">
<big>
<h2>Primitive and String Objects</h2>
<script type="text/javascript">
1
var first_string = "The winds of war are blowing.";
2
var next_string = new String("There is peace in the valley.");
3
document.write("The first string is of type<em> "+
typeof(first_string)
);
document.write(".</em><br />The second string is of type<em> "
4
+
typeof(next_string)
+".<br />");
</script>
</big>
</font>
</body>
</html>
EXPLANATION
1
This is the literal way to assign a string to a variable, and the most typical way. The
string is called a string primitive. It is one of the basic building blocks of the lan-
guage, along with numbers and Booleans. All of the properties and methods of the
String
object behave the same way whether you create a
String
literal or a
String
object as shown next. For all practical purposes, both methods of creating a string
are the same, though this one is the easiest.
2
The
String()
constructor and the
new
keyword are used to create a
String
object.
This is the explicit way of creating a string.
3
The
typeof
operator demonstrates that the first string, created the literal, implicit
way, is a
String
data type.
4
The
typeof
operator demonstrates that this string, created with the
String()
con-
structor, is an object type. Either way, when properties and methods are applied
to a string, it is treated as a
String
object (see Figure 9.27).