HTML and CSS Reference
In-Depth Information
EXAMPLE 17.2 ( CONTINUED )
2
var regex = new RegExp("love");
// Creating a regular
// expression object
3
if ( regex.test(myString)){
4
alert("Found pattern love!");
}
else{
5
alert("No match.");
}
</script>
</head>
<body></body>
</html>
EXPLANATION
1
The variable called myString is assigned “My gloves are worn for wear.”
2
The RegExp() constructor creates a new regular expression object, called regex .
This is the constructor way of creating a regular expression object. It is assigned
the string “love” , the regular expression.
3
The test() method for the regular expression object tests to see if myString con-
tains the pattern, love . If it finds love within gloves , it will return true .
4, 5
The alert dialog box will display Found pattern! if the test() method returned true ,
or No match. if it returns false . See Figure 17.3.
Figure 17.3 My gloves are worn for wear.” contains the pattern love .
The exec() Method. The exec() method executes a search to find a match for a spec-
ified pattern in a string. If it doesn't find a match, exec() returns null; otherwise it returns
an array containing the string that matched the regular expression.
FORMAT
array = regular_expression.exec(string);
EXAMPLE
list = /ring/.exec("Don't string me along, just bring me the goods.");
 
Search WWH ::




Custom Search