Java Reference
In-Depth Information
Although for basic searches the indexOf() method is fine, if you want more complex searches,
such as a search for a pattern of any digits or one in which a word must be in between a certain
boundary, search() provides a much more powerful and flexible, but sometimes more complex,
approach.
In the following example, you want to find out if the word Java is contained within the string.
However, you want to look just for Java as a whole word, not part of another word such as
JavaScript :
var myString = "Beginning JavaScript, Beginning Java 2, " +
"Professional JavaScript";
var myRegExp = /\bJava\b/i;
alert(myString.search(myRegExp));
First, you have defined your string, and then you've created your regular expression. You want
to find the character pattern Java when it's on its own between two word boundaries. You've
made your search case‐insensitive by adding the i after the regular expression. Note that with the
search() method, the g for global is not relevant, and its use has no effect.
On the final line, you output the position at which the search has located the pattern, in this case 32 .
the match() method
The match() method is very similar to the search() method, except that instead of returning the
position at which a match was found, it returns an array. Each element of the array contains the text
of a match made.
For example, if you had the string:
var myString = "The years were 2012, 2013 and 2014";
and wanted to extract the years from this string, you could do so using the match() method. To
match each year, you are looking for four digits in between word boundaries. This requirement
translates to the following regular expression:
var myRegExp = /\b\d{4}\b/g;
You want to match all the years, so the g has been added to the end for a global search.
To do the match and store the results, you use the match() method and store the Array object it
returns in a variable:
var resultsArray = myString.match(myRegExp);
To prove it has worked, let's use some code to output each item in the array. You've added an if
statement to double‐check that the results array actually contains an array. If no matches were
made, the results array will contain null —doing if (resultsArray) will return true if the
variable has a value and not null :
if (resultsArray) {
for (var index = 0; index < resultsArray.length; index++) {
 
Search WWH ::




Custom Search