Using String Objects in JavaScriptYou handle text strings in JavaScript using the String class. This class lets you create objects that can hold text strings, and it provides you with plenty of methods to let you work on those strings. You'll find the JavaScript methods of this class in Table 6-3 and the JScript methods of this class in Table 6-4. Table 6-3. Methods of the JavaScript String Class
Table 6-4. Methods of the JScript String Class
Here's an example. In this case, I'll create an object of the String class. Then I'll use the object's italics method to display it in italics, and its length property to find its length: Listing ch06_12.html<HTML> <HEAD> <TITLE> Using the String Class </TITLE> </HEAD> <BODY> <CENTER> </H1> Using the String Class <H1> </CENTER> <SCRIPT LANGUAGE = "JavaScript"> var string1 = new String("JavaScript and XML are a good mix") document.writeln("The text string, " + string1.italics() + ", is " + string1.length + " characters long.") </SCRIPT> </BODY> </HTML> In this case, I'm passing the text I want in the string "JavaScript and XML are a good mix" to the String class's constructor. That constructor creates a new String object with that text in it and returns it. Now I'm able to use the new object's italics method to display the string in italics, and I can use the length property to determine the string's length. You can see the results in Figure 6-12. Figure 6-12. Using the String class in Internet Explorer.
Here's another important aspect of the String class: JavaScript treats this class in a special way, which means that you can actually use it without the new operator. You can declare an object of the String class as a normal variable (without using the new operator or even mentioning the String class), and JavaScript will know just what you mean. Behind the scenes, it uses the String class, but you never need to know it, as in this code: <HTML> <HEAD> <TITLE> Using the String Class </TITLE> </HEAD> <BODY> <CENTER> <H1> Using the String Class </H1> </CENTER> <SCRIPT LANGUAGE = "JavaScript"> var string1 = "JavaScript and XML are a good mix" document.writeln("The text string, " + string1.italics() + ", is " + string1.length + " characters long.") </SCRIPT> </BODY> </HTML> |