Java Reference
In-Depth Information
In this chapter you look at four new methods of the String object, namely split() , match() ,
replace() , and search() . The last three, in particular, give you some very powerful text‐
manipulation functionality. However, to make full use of this functionality, you need to learn about
a slightly more complex subject.
The methods split() , match() , replace() , and search() can all make use of regular expressions ,
something JavaScript wraps up in an object called the RegExp object. Regular expressions enable
you to define a pattern of characters, which you can use for text searching or replacement. Say, for
example, that you have a string in which you want to replace all single quotes enclosing text with
double quotes. This may seem easy—just search the string for ' and replace it with " —but what if
the string is Bob O'Hara said "Hello" ? You would not want to replace the single‐quote character
in O'Hara . You can perform this text replacement without regular expressions, but it would take
more than the two lines of code needed if you do use regular expressions.
Although split() , match() , replace() , and search() are at their most powerful with regular
expressions, they can also be used with just plaintext. You take a look at how they work in this
simpler context first, to become familiar with the methods.
additional string methods
In this section you take a look at the split() , replace() , search() , and match() methods, and see
how they work without regular expressions.
the split() method
The String object's split() method splits a single string into an array of substrings. Where
the string is split is determined by the separation parameter that you pass to the method. This
parameter is simply a character or text string.
For example, to split the string "A,B,C" so that you have an array populated with the letters between
the commas, the code would be as follows:
var myString = "A,B,C";
var myTextArray = myString.split(",");
JavaScript creates an array with three elements. In the first element it puts everything from the start
of the string myString up to the first comma. In the second element it puts everything from after the
first comma to before the second comma. Finally, in the third element it puts everything from after
the second comma to the end of the string. So, your array myTextArray will look like this:
A B
C
If, however, your string were "A,B,C," JavaScript would split it into four elements, the last element
containing everything from the last comma to the end of the string; in other words, the last string
would be an empty string:
A B C
This is something that can catch you off guard if you're not aware of it.
 
Search WWH ::




Custom Search