HTML and CSS Reference
In-Depth Information
EXAMPLE
17.3
<html>
<head><title>The exec() method</title>
<script type="text/javascript">
1
var myString="My lovely gloves are worn for wear, Love.";
2
var regex = /love/i;
//
Create a regular expression object
3
var array=regex.exec(myString);
4
if (
regex.exec(myString
)){
alert("Matched! " + array);
}
else{
alert("No match.");
}
</script>
</head>
<body></body>
</html>
EXPLANATION
1
The string
“My gloves are worn for wear.”
is assigned to
myString
.
2
The regular expression
/love/
is assigned to the variable
regex
.
3
The
exec()
method returns an array of values that were found.
4
If the
exec()
method doesn't return
null
, then there was a match. See Figure 17.4.
Figure 17.4
The array returned by
exec()
contains
love
.
There are two types of properties that can be applied to a
RegExp
object. The first type is
called a
class property
(see Table 17.3) and applies to the
RegExp
object as a whole, not
a simple instance of a regular expression object. The
input
property is an example of a
class property. It contains the last string that was matched, and is applied directly to the
RegExp
object as
RegExp.input
.
The other type of property is called an
instance property
and is applied to an instance
of the object (see Table 17.4); for example,
mypattern.lastIndex
refers to the position
within the string where the next search will start for this instance of the regular expres-
sion object, called
mypattern
. These properties will be explained in examples throughout
this chapter.