Regular expressions in Javascript are represented by a RegExp
object. There also is a regex literal as in many other languages: /regex/
. However, they are used slightly differently.
/foo+/
RegExp("foo+")
or new RegExp("foo+")
RegExp("\\d+")
/regex/.test(...)
is converted to a string
as defined by the specs
Show archive.org snapshot
, which means e.g. .test(null)
is equal to .test("null")
.test()
will advance this pointer:matcher = new RegExp("foo", "g") // <- "global" flag
matcher.test("foobar") // => true
matcher.lastIndex // => 3 (where the regexp stopped scanning)
matcher.test("foobar") // => false
matcher.lastIndex // => 0
This does not happen when creating a new regex object each run, as with /foo/g.test("foobar")
. Use String#match()
if you want an array of matches.