JavaScript RegExp Object
A RegExp is a regular expression: a pattern used to search, match and replace text. Patterns are written between slashes, such as /\d+/g, and used with methods like test(), match() and replace().
Description
A RegExp object holds a regular expression, a pattern for matching text. Write one as a literal between slashes, /colou?r/i, or build one from a string with new RegExp() when the pattern isn't known in advance (remember to escape backslashes in the string). Flags after the pattern change how it works: g finds all matches, i ignores case, m makes ^ and $ match at line breaks, s lets . match newlines, u and v enable Unicode features, y is sticky and d adds match indices.
Regular expressions are used with RegExp methods such as test() and exec(), and with string methods such as match(), matchAll(), replace(), search() and split(). A regex with the g or y flag remembers its position in lastIndex, which can cause surprising results if you reuse it with test().
Capture groups, written with parentheses, let you pull parts out of a match, and named groups, (?<year>\d{4}), make the result easier to read through the groups property. Lookaheads and lookbehinds, such as (?=...) and (?<=...), check what comes before or after a position without including it in the match. Regular expressions can be hard to read, so keep them short, add comments nearby, and test them with sample input.
Creating
/pattern/flags
new RegExp(pattern, flags)Instance properties
| Name | Description |
|---|---|
RegExp.prototype.lastIndex | The lastIndex property holds the position where a global or sticky regular expression will start its next search. |
Instance methods
| Name | Description |
|---|---|
RegExp.prototype.exec() | The exec() method searches a string for a regular expression match and returns details of the match, including capture groups. |
RegExp.prototype.test() | The test() method checks whether a regular expression matches a string, returning true or false. |
Example
Browser Support
The following information will show you the current browser support for the RegExp object. Hover over a browser icon to see the version that first introduced support for this object.
Desktop





Tablets & Mobile





