test()

The test() method is ued with the RegExp object to test for a pattern match within a given string. If a match is found the test() method will return a value of true if it finds a match, and false if it doesn't find a match. This is useful when the need arises to write a text message to the screen if a match is found, and another text message if no match is found - an if / else statement fits with this method quite nicely, as you'll see in the example.

syntax:

regExpName.test(stringName)

EXAMPLE

searchString = new RegExp("is");

stringToSearch = "This the string of text to search.";

if (searchString.test(stringToSearch) ) {

document.write("The test() method found the matches!")

} else {

document.write("The test() method found no matches!")

}

The example shows the creation of a new RegExp object called searchString, which is searching for the word "is" in the string of text called stringToSearch. The condition of the if statement uses the RegExp object name searchString with the test() method. Notice that the stringToSearch is within the brackets of the test method. The method will then test the string represented by the stringToSearch object. If a match is found and the test() method returns a true, the if / else statement returns the first document.write statement. If no match is found and the test() method returns false, the second document.write statement is written to the screen.