Regular expressions
A regular expression is a succinct way of describing strings, typically used in searching for a pattern, subject to modifiers that indicate when the pattern should apply. The syntax used is /pattern/modifiers
.
Modifiers
The following modifiers can be used, singly or in combination.
Modifier | Meaning |
---|---|
i |
(case-insensitive) |
g |
(global, find all matches) |
m |
(multiline matching) |
For example, /a/g
can be used to find lower-case a's, and /a/gi
can be used to find lower-case a's and upper-case A's. Similarly, a string can be used instead of a single character, such as /out/g
being used to find all matches with the string "out"
.
Methods using regular expressions
The string method .search(exp)
consumes a regular expression and produces the position of the first match, and the string method .replace(exp, replace)
consumes a regular expression and replacement string and produces the string formed by replacing each substring matching the pattern by the replacement string.
For a string stored in the variable example
:
example.search(/a/)
finds the position of the first lower-case aexample.replace(/a/g/, "?")
replaces each lower-case a with a question markexample.search(/a/i)
find the position of the first a, lower-case or upper-caseexample.replace(/the/gi, "?")
replaces the stringthe
with a question mark, whether the letters are lower-case or upper-case