RegExp object. There also is a regex literal as in many other languages:
/regex/. However, they are used slightly differently.
- Shorthand for creating a regular expression object
- No surrounding slashes required (they're the literal markers)
- Since the argument is a string, backslashes need to be escaped as well:
The argument to
/regex/.test(...)is converted to a string , which means e.g.
.test(null)is equal to
Globally matching regex objects. Multiple calls to
test()will advance this pointer:Copy
> 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
String#match()if you want an array of matches.
- There is that offers more options and looks promising (untested). Supports all browsers from IE5.