Regular expressions are patterns used to match character combinations in strings. In
JavaScript, regular expressions are also objects. For example, to search for all
occurrences of 'the' in a string, you create a pattern consisting of 'the' and use the
pattern to search for its match in a string. Regular expression patterns can be
constructed using literal notation (for example, /abc/
) or the RegExp
constructor function (for example, re = new RegExp("abc")
).
These patterns are used with the exec
and test
methods of
regular expressions, and with the match
, replace
, search
,
and split
methods of String
.
When the search for a match requires something more than a direct match, such as
finding one or more b's, or finding whitespace, the pattern includes special characters.
For example, the pattern /ab*c/
matches any character combination in which a
single 'a' is followed by zero or more 'b's (*
means 0 or more occurrences of
the preceding character) and then immediately followed by 'c'. In the string
"cbbabbbbcdebc," the pattern matches the substring 'abbbbc'.
As shown in the second form of this example, you can use the literal form of a regular
expression without assigning it to a variable. If you do, however, every occurrence of the
literal is a new regular expression. For this reason, if you use the literal form without
assigning it to a variable, you cannot subsequently access the properties of that regular
expression. For example, assume you have this script:
Including parentheses in a regular expression pattern causes the corresponding submatch
to be remembered. For example, /a(b)c/
matches the characters 'abc' and
remembers 'b'. To recall these parenthesized substring matches, use the RegExp
properties $1
, ..., $9
or the Array
elements [1]
,
..., [n]
.