JavaScript RegExp Methods
Regular expressions in JavaScript are a powerful way to search, match, and manipulate strings. In this guide, we will focus on the key methods associated with
Regular expressions in JavaScript are a powerful way to search, match, and manipulate strings. This guide covers the key methods you call on a regular expression (test, exec) and on a string (search, split, match, matchAll, replace, replaceAll), with a runnable example and the real return shape for each. Understanding these methods lets you efficiently handle pattern matching in your code.
A quick regex refresher
Before the methods, a one-minute orientation for readers new to regular expressions.
A regex literal is written between slashes, optionally followed by flags:
/pattern/flags // e.g. /hello/giYou can also build one dynamically with the RegExp constructor, which is useful when the pattern comes from a variable (note that backslashes must be doubled inside a string):
const word = "hello";
const regex = new RegExp(word, "gi"); // same as /hello/gi
const digits = new RegExp("\\d+"); // same as /\d+/The flags change how matching behaves:
| Flag | Name | Effect |
|---|---|---|
g | global | Find all matches instead of stopping at the first. |
i | ignore case | Make matching case-insensitive. |
m | multiline | ^ and $ match at line breaks, not just string ends. |
s | dotAll | Let . also match newline characters. |
u | unicode | Treat the pattern as a sequence of Unicode code points. |
y | sticky | Match only starting exactly at lastIndex. |
For the full pattern syntax and flag details, see JavaScript Patterns and Flags and Capturing Groups. Many of the methods below are also documented from the string side in JavaScript Strings.
RegExp.test()
The test() method tests a string for a match against a regular expression. It returns true if a match is found, or false otherwise.
Example
In this example, the test() method checks if the string "Hello world!" contains the pattern "hello". Since the method is case-sensitive, it returns false. Add the i flag (/hello/i) and it would return true.
RegExp.exec()
The exec() method searches a string for a match against a regular expression. It returns an array containing the matched text and capture groups, or null if no match is found. The returned value is not a plain array: it also carries index (where the match started), input (the original string), and groups (named capture groups, or undefined if there are none).
Example
Here exec() finds one or more digits in "The year is 2024." Element 0 is the full match, element 1 is the first capturing group (\d+), and the extra properties tell you where the match was found.
The lastIndex gotcha with /g
When the regex has the global (g) or sticky (y) flag, exec() becomes stateful: each call resumes from the regex's lastIndex property and advances it, returning null once there are no more matches. Call it in a loop to walk through every match — but be aware that reusing the same /g regex across unrelated calls can give surprising results because lastIndex is remembered.
Without the g flag, exec() is not stateful and always returns the first match, so a while loop like this would run forever. For non-global use, prefer match() or matchAll().
String.search()
The search() method tests a string for a match against a regular expression. It returns the zero-based index of the first match, or -1 if no match is found.
Example
In this example, the search() method returns the index of the first occurrence of "awesome" in the string, which is 14.
String.split()
The split() method divides a string into an ordered list of substrings and returns them in an array. It is a general-purpose string method: the separator can be a plain string (str.split(",")) or a regular expression. The regex form is just one use case, handy when the delimiter varies — for example, splitting on one or more whitespace characters.
Example
The first call splits on a literal comma; the second uses the regex /\s+/ to split on any run of whitespace, so multiple spaces and tabs collapse into clean separators.
String.match()
The match() method retrieves the result of matching a string against a regular expression. Its return value depends on the flags:
- With
/g: an array of all matched substrings (noindexorgroups), ornullif there are no matches. - Without
/g: the same rich arrayexec()returns — the first match plus capture groups, withindex,input, andgroups— ornullif there is no match.
Because match() returns null rather than an empty array when nothing matches, always check the result before using it.
Example
With the global flag, match() returns every occurrence of "ain"; a pattern that does not match returns null, not an empty array.
String.matchAll()
The matchAll() method returns an iterator of all matches, including capturing groups. Each item it yields is a full match array (a RegExpMatchArray), the same shape exec() produces — so every match carries index, input, and groups, not just the matched strings. The regular expression must have the g flag, or matchAll() throws a TypeError. Unlike exec() in a loop, matchAll() does not leave a leftover lastIndex on your regex, which makes it the cleaner choice for iterating over every match. (Requires ES2020+.)
Example
Because the items are real match arrays, you can read match.index and the captured groups (match[1], match[2], …) for each result. Convert the iterator to an array with Array.from(str.matchAll(regex)) or the spread operator when you need to index into the results.
String.replace()
The replace() method returns a new string with matches of the pattern replaced (the original string is never mutated). With a plain string or a regex without /g it replaces only the first match; add the g flag to replace all of them.
The replacement string supports special tokens: $& is the whole match, $` and $' are the text before/after it, $n inserts the nth capturing group, and $<name> inserts a named group.
Example
You can also pass a function as the replacement; it receives the match and captured groups as arguments and returns the replacement text, which is handy for computed values:
String.replaceAll()
The replaceAll() method replaces every occurrence and returns a new string. When you pass it a regular expression, that regex must have the g flag or it throws a TypeError — this guards against the common mistake of expecting replace() to be global. It supports the same $1 / $<name> replacement tokens and function replacers as replace(). (Requires ES2021+.)
Example
Use replaceAll() with a plain string when you simply want to swap all copies of a literal substring; reach for the regex form when the target is a pattern.
Conclusion
This guide covered the primary methods used with regular expressions in JavaScript — test and exec on the regex side, and search, split, match, matchAll, replace, and replaceAll on the string side — along with their real return shapes and the stateful lastIndex behavior of the /g flag. To go deeper into the patterns themselves, continue with Patterns and Flags, Capturing Groups, and the sticky y flag.