Полезная информация

JavaScript: The Definitive Guide

Previous Chapter 3
Variables and Data Types

3.3 Strings

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:

There are a number of methods that you can use to operate on strings. For example, to find out what the last character of a string s is, you could use:

last_char = s.charAt(s.length - 1)
To extract the second, third, and fourth characters from a string s, you would write:

sub = s.substring(1,4);
To find the position of the first letter `a' in a string s, you could use:

i = s.indexOf('a');
There are quite a few other methods you can use to manipulate strings. You'll find full documentation of these methods in the reference section of this book, under the headings "String", "String.charAt", and so on.

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.

Previous Home Next
Numbers Book Index boolean Values

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell