∟The "String" Object Type - Not Equal to String Primitive Type
This section provides a quick description and a tutorial example script on the 'String' built-in object type, which is used to create 'String' objects. Watch out: 'String' objects are not string values.
The "String" object type is a special built-in object type to be used to create a "String" object,
which is different than a string value of the string primitive type.
It has the following main features:
New "String" objects can be created with the "String()" constructor. Note that "String()" is also a regular function,
which returns a string value, not a "String" object.
All "String" objects have an inherited property called "length" representing the number of characters of the string.
All "String objects have many inherited methods: toString(), charAt(), charCodeAt(), concat(), indexOf(), etc..
Accessing those inherited methods is the main reason of using "String" objects instead of string values.
A string literal, "...", creates a string value, not a "String" object.
A string value can be converted to a "String" object on the fly with the (.) operator, for example: "string".length.
Here is a tutorial example script showing some of the those features:
// String_Object_Type.html
// Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
// Creating a new String object
var message = new String("Hello World!");
// Checking this object
println("\nAbout this \"message\":");
println(" Type = "+(typeof message));
println(" Instance Of Object: "+(message instanceof Object));
println(" Instance Of String: "+(message instanceof String));
// Using String's inherited property and method
var upperMessage = message.toUpperCase();
var l = message.length;
var subMessage = message.substring(0,l-7);
println("\nExecution result:");
println(" typeof message = "+(typeof message));
println(" message.toString() = "+message.toString());
println(" typeof upperMessage = "+(typeof upperMessage));
println(" upperMessage = "+upperMessage);
println(" typeof subMessage = "+(typeof subMessage));
println(" subMessage = "+subMessage);
println("\nConverting to String objects on the fly:");
println(" \"...\".length = "+("Hello World!".length));
println(" \"...\".toUpperCase() = "
+("Hello World!".toUpperCase()));
If you run this script with "jrunscript", you will get:
About this "message":
Type = object
Instance Of Object: true
Instance Of String: true
Execution result:
typeof message = object
message.toString() = Hello World!
typeof upperMessage = string
upperMessage = HELLO WORLD!
typeof subMessage = string
subMessage = Hello
Converting to String objects on the fly:
"...".length = 12
"...".toUpperCase() = HELLO WORLD!
Now we know how to create "String" objects with the "String()" constructor.
Read other "String" related chapters to see more tutorial examples.