HTML and CSS Reference
In-Depth Information
The
RegExp
object has two methods that can be used to test for a match in a string,
the
test()
method and the
exec()
method, which are quite similar. The
test()
method
searches for a regular expression in a string and returns
true
if it matched and
false
if
it didn't. The
exec()
method also searches for a regular expression in a string. If the
exec()
method succeeds, it returns an array of information including the search string,
and the parts of the string that matched. If it fails, it returns
null
. This is similar to the
match()
method of the
String
object. Table 17.2 summarizes the methods of the
Reg-
Exp
object.
Table 17.2
Methods of the
RegExp
Object
Method
What It Does
exec
Executes a search for a match in a string and returns an array.
test
Tests for a match in a string and returns either
true
or
false.
The
test()
Method.
The
RegExp
object's
test()
method is used to see if a string con-
tains the pattern represented in the regular expression. It returns a
true
or
false
Bool-
ean value. After the search, the
lastIndex
property of the
RegExp
object contains the
position in the string where the
next
search would start. (A string starts at character
position 0.) If a global search is done, then the
lastIndex
property contains the starting
position after the last pattern was matched. (See Example 17.4 to see how the
lastIndex
property is used.)
Steps to test for a match:
1. Assign a regular expression to a variable.
2. Use the regular expression
test()
method to see if there is a match. If there is a
match, the
test()
method returns
true
; otherwise, it returns
false
. There are also
four string methods that can be used with regular expressions. (See section
“String Methods Using Regular Expressions” on page 727.)
FORMAT
var string="String to be tested goes here";
var
regex
= /regular expression/;
//
Literal way
var
regex
=new RegExp("regular expression");
//
Constructor way
regex.test
(string);
//
Returns either true or false
or
/regular expression/.test("string");