A string is a string of letters, digits, punctuation characters, and so on--it is the JavaScript data type for representing text. As we saw in Chapter 2, Lexical Structure, string literals may be included in your programs by enclosing them in matching pairs of single or double quotes.
One of the built-in features of JavaScript is the ability to concatenate strings. If you use the + operator with numbers, it adds them. But if you use this operator on strings, it joins them by appending the second to the first. For example:
msg = "Hello, " + "world"; // produces the string "Hello, world" greeting = "Welcome to my home page," + " " + name;
To determine the length of a string--the number of characters it contains--you use the length property of the string. If the variable s contains a string, you access its length like this:
s.length
last_char = s.charAt(s.length - 1)
sub = s.substring(1,4);
i = s.indexOf('a');
When we introduce the object data type below, you'll see that object properties and methods are used in the same way that string properties and methods are used in the examples above. This does not mean that strings are a type of object. In fact, strings are a distinct JavaScript data type. They use object syntax for accessing properties and methods, but they are not themselves objects. We'll see just why this is at the end of this chapter.
Note that JavaScript does not have a char or character data type, like C, C++, and Java do. To represent a single character, you simply use a string that has a length of 1.
This HTML Help has been published using the chm2web software. |