Pattern validation
Validate or detect text patterns such as identifiers, tokens, or simple formats.
JavaScript · Class
RegExp represents a pattern for matching text. Create it with literal syntax or the constructor, then use it with RegExp and String matching methods.
RegExp represents a pattern used to search text. Create one with slash notation or the constructor; the constructor accepts a pattern and optional flags, and instances provide matching methods such as test() and exec().
new RegExp(pattern)
new RegExp(pattern, flags)
RegExp(pattern)
RegExp(pattern, flags)| Name | Type | Description |
|---|---|---|
pattern | string | RegExp | The pattern to compile, supplied as a string or a RegExp object. |
flags | string | Optional flags that modify interpretation or interaction with input text. |
A RegExp object representing the compiled pattern; in the special RegExp(pattern) case, the supplied RegExp may be returned directly.
const word = new RegExp("cat", "gi");
console.log(word.test("A CAT sleeps.")); // true
console.log(word.flags); // "gi"
console.log(word.source); // "cat"Creates a case-insensitive, global regular expression and tests whether the input contains a matching word.
Validate or detect text patterns such as identifiers, tokens, or simple formats.
Extract matching portions and capture groups from input strings.
Perform replacements, searches, splitting, or iteration over matches.
RegExp objects describe text-matching patterns. They can be created with a literal such as /ab+c/g or with new RegExp(pattern, flags), which is useful when the pattern is assembled dynamically.
Follow-up: When is the constructor preferable to a literal? Use it when the pattern or flags come from runtime values; remember that string escaping rules apply before the regular-expression parser sees the pattern.
The first constructor argument is the pattern, which may be a string or another RegExp object. The optional second argument is a string containing flags that affect matching behavior.
Follow-up: What happens when a RegExp pattern is passed without new? If the pattern is already a RegExp and flags are undefined, the existing pattern may be returned directly; otherwise a new RegExp object is created.
A regular expression can be used with instance methods such as test() to check for a match or exec() to obtain match information. It also interoperates with String methods including match(), replace(), search(), and split().
Follow-up: Why can repeated test() calls differ for /x/g? Global matching advances lastIndex after successful matches, so later calls resume from the stored position.
RegExp.prototype.exec()RegExp.prototype.test()RegExp.prototype.compile()RegExp.prototype.dotAllRegExp.prototype.flagsRegExp.prototype.globalRegExp.prototype.hasIndicesRegExp.prototype.ignoreCase