I recently covered the very basics of regular expression syntax. Now I’ll describe a little bit about how regular expressions work in JavaScript.
The simplest method on the RegExp object is test
which returns true
if the string contains the specified regular expression.
/[A-Z]+/.test('Foo') // true
The exec
method returns an array with the first match or null
if there was no match.
/[a-z]+.exec('foo bar') // returns Array['foo']
That array also contains the index of where the match was found (0 in this case) and the input string (‘foo bar’).
To do the match more than once, you can use the g
flag and call exec
repeatedly.
let lower = /[a-z]+/g
lower.exec('foo bar') // null
lower.exec('foo bar') // bar
lower.exec('foo bar') // foo
An easier way to get all of the matches is the use the match
method on the string class. If you use the g
flag, all of the matches are returned in an array.
'foo bar'.match(/a-z]+/g) // Array['foo', 'bar']
The matchAll
method on the String
class returns an iterable which can be very nice.
for (a of 'foo bar'.matchAll(/[a-z]+/g)) {
console.log(a)
}
A good property of the matchAll
method is that it uses lazy evaluation so that it can be very efficient if only a few initial matches are needed.
The replace
method replaces the first match with a replacement string. If you set the g
flag, all of the matches will be replaced.
'foo bar'.replace(/[a-z]+/g, 'x') // 'x x'
There are some more subtleties about the RegExp
and String
objects but this covers the very basics.