HTML and CSS Reference
In-Depth Information
EXAMPLE 17.4
<html>
<head>
<title>The test() method</title>
</head>
<body bgcolor="silver">
<font face="arial" size="+1">
<script type = "text/javascript">
1
var myString="I love my new gloves!";
2
var regex = /love/g;
// Create a regular expression object
3
var booleanResult = regex.test(myString);
if ( booleanResult != false ){
4
document.write("Tested regular expression <em>"+
regex.source + ".</em> The result is <em>"
+ booleanResult + "</em>");
document.write(".<br>Starts searching again at position " +
5
regex.lastIndex + " in string<em> \"" +
6
RegExp.input + "\"<br />");
document.write("The last matched characters were: "+
7
RegExp.lastMatch +"<br />");
document.write("The substring preceding the last match is:
8
"+ RegExp.leftContext +"<br />");
document.write("The substring following the last match is:
9
"+ RegExp.rightContext +"<br />");
}
else{ alert("No match!"); }
</script>
</font>
</body>
</html>
EXPLANATION
1
The string object to be tested is created.
2
A regular expression object, called regex , is created.
3
The test() method returns true or false if the regular expression is matched in the
string.
4
The source property is applied to regex , an instance of a RegExp object. It contains
the text of the regular expression, / love /.
5
The lastIndex property is applied to an instance of a RegExp object. It represents
the character position right after the last matched string.
6
The input class property represents the input string on which the pattern match-
ing (regular expression) is performed.
7
lastMatch is a class property that represents the characters that were last matched.
 
Search WWH ::




Custom Search