match()

The match() method is used to find a match within the given string (stringName - see syntax) using the regular expression given within the parentheses (regularExpression - see syntax). The method then returns an array containing the matches found within the string. For a full explanation of regular expressions and the RegExp object, see the JavaScript Object Reference, RegExp and regular expression.

syntax:

stringName.match(regularExpression)

EXAMPLE

var stringToSearch = new String("This is the string of text that will be searched");

var theRegExp = /\s\w*/g;

var searchArray = stringToSearch.match(theRegExp);

if (searchArray == null) {

document.write("No matches were found");

} else {

document.write("The following matches were found within the text :
")

for (var n = 0; n < searchArray.length n++) {

document.write(searchArray[n] + "
");

}

}

The example is very complicated, but also very functional. The code was started with the creation of a new string called stringToSearch. Next came the regular expression which was named theRegExp. After the declaration of the regular expression, the array the results are to be put in is created, called searchArray. The condition of the array was executed to find a match using the match() method with theRegExp within parentheses as the parameter. An if / else statement was then used to write one message to the screen if a mtach was found and one if no match was found. If a match is found, then the for statement accesses the searchArray array and displays the contents of the array, each item on a separate line. The output of the above code is shown below:



The following matches were found within the text :



is

the

string

of

text

that

will

be

searched