There are three possible flags:
i: Ignore case
g: Global match
m:Match over multiple lines
The second way to declare a regular expression is to use the literal format:
var re = /regex/ig;
The literal format does not have quotes around it; it is surrounded by the forward slash.
The flags appear immediately after the regular expression.
The regular expression is meant to be used against a string. A regular expression object
has two main functions: exec and test.
exec performs a search on a string and returns an array of matches. test returns true if a
match is found and false otherwise. Here is a common way to test a possible American or
Canadian phone number format:
var phonenumber = '613-555-1212';
/^\d{3}-\d{3}-\d{4}$/.test(phonenumber); // returns true
The match, search, and replace methods of the built-in String object accept regular
expressions as parameters:
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 37
??? match behaves like exec by returning an array of results that match the regular
expression.
??? search returns the index in which it could find a match within the string or returns -1
if no match is found.
??? replace replaces the substring match with the characters of your choosing. An example
is rearranging a date format:
var dt = '12-01-2007';
dt.replace(/^(\d{2})-(\d{2})-(\d{4})$/, '$3$2$1'); // returns 20070112
A regular expression starts at the beginning of a string and works its way through trying to
match to the pattern defined.
Pages:
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87