The String Object
One way to create a String object is to use the new keyword. The syntax is shown here:
var instance_name = new String("string value here");
You replace instance_name with the name you want to use for the instance of the String object. You then replace string value here with the string of characters to use as the new String object. So, if you want to create an instance of the String object named guitar_string, you could use the following code:
var guitar_string = new String("G");
This script creates an instance of the String object for the string “G”. Although creating a String object with the new keyword can be useful for things such as comparing String objects, string literals are used more often.
The String Literal
You can create a string literal just by assigning a string value to a variable. This technique is a bit shorter than creating a String object using the new keyword and still allows you to use all the methods of the String object (as well as one of the properties).
A string literal is created in the code that follows. Notice that the code assigns a string value to a variable.
var guitar_string = "G";
This makes the string “G” a string literal, which you know as a regular text string. With text strings, you’re also allowed to use the properties and methods of the String object.
What’s the Difference?
The difference between a String object and a string literal is that a regular text string has the value of the string itself, and it can be compared against another string easily, as in the following code:
Because this code uses regular string literals, the result is what you’d expect. An alert says that the strings are the same.
However, if you used String objects to run through the same if block, you would see something unexpected. The code that follows uses String objects instead:
This time the alert would tell you that the strings are not the same, even though the string values are both “E” because a String object is an object value and not a literal value. Objects aren’t going to be equal to one another in the same way regular text strings would be. To find out if two objects are equal, you would have to write extra code to determine that. For most purposes, you wouldn’t want to go to all that trouble. Instead, you would probably use string literals and let them use the String object’s methods.
The String object has only three properties.
The String object has a lot of methods, yes, this list is quite long!