Java Reference
In-Depth Information
The same principle is used for the case-insensitive and multi-line fl ags.
Okay, back to the
doTest()
function. The regular expression object has been created and its fl ags have
been set, so now you test to see if the regular expression matches anything in the Test Text box.
if ( testRegExp.test(document.form1.txtTestString.value) )
{
document.form1.txtTestResult.value = “Match Found!”;
}
else
{
document.form1.txtTestResult.value = “Match NOT Found!”;
}
If a match is found, “Match Found!” is written to the Results box; otherwise “Match NOT Found!” is
written.
The regular expression object's
test()
method is used to do the actual testing for a match of the regu-
lar expression with the test string supplied as the method's only parameter. It returns
true
when a
match is found or
false
when it's not. The global fl ag is irrelevant for the
test()
method, because it
simply looks for the fi rst match and returns
true
if found.
Now let's look at the findMatches() function, which runs when the cmdMatches button is clicked.
As with the doTest() function, the fi rst line creates a new regular expression object with the regular
expression entered in the Regular Expression text box in the form and the fl ags being set via the
getRegExpFlags() function.
var testRegExp = new RegExp(document.form1.txtRegularExpression.value,
getRegExpFlags());
Next, a new
String
object is created, and you then use the String object's
match()
method to fi nd the
matches.
var myTestString = new String(document.form1.txtTestString.value)
var matchArray = myTestString.match(testRegExp);
The match() method returns an array with all the matches found in each element of the array. The
variable matchArray is used to store the array.
Finally, the match results are displayed in the Results box on the form:
document.form1.txtTestResult.value = matchArray.join('\n');
The String object's join() method joins all the elements in an array and returns them as a single
string. Each element is separated by the value you pass as the join() method's only parameter. Here \n
or the newline character has been passed, which means when the string is displayed in the Results box,
each match is on its own individual line.