
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Working with Strings
|
101
Combining String Examination with Substring Extraction
We’ve seen how to search for characters in a string and how to extract characters
from a string. These two operations are most powerful when we put them together.
Most of the examples we’ve seen so far use literal expressions as arguments, like this:
var msg = "Welcome to my website!";
var firstWord = msg.substring(0, 7); // 0 and 7 are numeric literals
That’s a decent demonstration of the way substring() works, but it doesn’t represent
the typical real-world use of substring(). More often, we don’t know the content of
the string in advance and we must generate our arguments dynamically. For exam-
ple, instead of saying something static like, “Get me the substring from index 0 to
index 7,” we usually say something dynamic like, “Get me the substring starting
from the first character and ending at the first occurrence of a space in this string.”
This more flexible approach doesn’t require us to know the content of a string in
advance. Here we extract the first word of the variable
msg, by combining substring()
with indexOf():
var firstWord = msg.substring(0, msg.indexOf(" "));
The expression msg.indexOf(" ") evaluates to the numeric index of the first space in
msg. Our technique will work regardless of the