JavaScript’s String.prototype.match() method searches a string using a regular expression and returns information about the match, or null if it finds none. Use text.match(pattern) for a quick search; the regular expression’s flags determine whether the result contains one match or every match.
How String.match() works
match() is a string method that works with regular expressions. It does not change the original string. In common use, pass a regular expression literal between slashes, such as /cat/, or create a regular expression with the RegExp constructor. The method returns an array when it finds a match and null when it does not.
For example, 'A cat naps'.match(/cat/) returns an array whose first item is 'cat'. The method is useful when you want to find a pattern and inspect what was found, not just ask whether a pattern exists.
Behind the scenes, JavaScript calls the regular expression’s Symbol.match method. Built-in regular expressions provide that behavior, and custom objects can also define it. This detail usually matters only when extending or implementing unusual matching behavior; everyday code can treat match() as a regular-expression search.
Syntax and the returned value
The usual syntax is string.match(regexp). The argument is normally a regular expression, though a string or another value is converted to a regular expression in ordinary cases. That conversion can surprise you: a string passed as the pattern is not automatically treated as a literal phrase.
With a regular expression that does not have the global flag, the result is an array with useful properties:
- Item zero contains the complete match.
- Further items contain any capturing groups, in order.
indexgives the starting position of the match in the original string.inputcontains the original string.groupscontains named captures when the pattern defines them; otherwise it isundefined.
For instance, 'Order 482'.match(/Order (\d+)/) has 'Order 482' at index zero and '482' at index one. Its index is 0. If you only need the full match, you can read result[0]; if you need a capture, use its numbered index or named group.
When no match exists, the result is null, not an empty array. Check for that before reading properties or indexes. A common safe pattern is const result = text.match(pattern); if (result) { /* use result */ }.
Global and non-global regular expressions
The g flag changes the shape and purpose of the result. Without g, match() returns the first match, along with captured groups and the metadata described above. With g, it returns an array of all complete matches, in order, or null if there are none.
For example, 'red 12, blue 34'.match(/\d+/) returns a match array for '12'. By contrast, 'red 12, blue 34'.match(/\d+/g) returns ['12', '34']. In the global result, capture groups are not included, and properties such as index and input are not provided. That difference is a frequent source of bugs when code starts using the g flag.
For a global regular expression, match() searches from the beginning of the string rather than continuing from an earlier lastIndex value. If your code needs every match and the capture groups for each one, consider matchAll(), discussed below.
Practical examples
Regular expressions describe patterns rather than only fixed words. The following examples show common uses. They assume the input is a JavaScript string and that you want to examine the returned value.
- Find digits:
'Room 27'.match(/\d+/)finds the consecutive digits'27'. The+means one or more digits. - Find every word-like run:
'one two'.match(/\w+/g)returns['one', 'two']. In JavaScript,\wprincipally matches ASCII letters, digits, and underscore; it is not a general match for every letter in every writing system. - Ignore letter case:
'JavaScript'.match(/javascript/i)finds the text despite the capitalization difference. Theiflag makes matching case-insensitive. - Capture part of a value:
'2026-11'.match(/(\d{4})-(\d{2})/)returns the full date-like text, followed by captures for2026and11. - Use a named capture:
'2026-11'.match(/(?<year>\d{4})-(?<month>\d{2})/)makes the captured parts available by name throughresult.groups.yearandresult.groups.month.
A pattern is not necessarily a whole-string check. For example, /cat/ also matches the letters in 'catalogue'. Add anchors when you need to require a match at a particular boundary: /^cat$/ matches only a string consisting of cat, because ^ and $ mark the beginning and end of the input.
Capturing groups and matchAll()
Parentheses in a regular expression create capturing groups by default. They let you extract parts of a match, such as a year from a date or a number from a label. If parentheses are needed only to group alternatives or apply a quantifier, use a non-capturing group, written (?:...), so the result does not gain an unwanted numbered capture.
When you need all matches and their captures, call matchAll() with a global regular expression. It returns an iterator, so convert it to an array if you want to inspect all results at once:
const matches = [...'x=10, y=25'.matchAll(/([a-z])=(\d+)/g)];
Each item in matches is a match array that includes the complete match and its captures, as well as information such as its index. Unlike a global match() result, this preserves captures for every occurrence. matchAll() requires the regular expression to have the g flag; without it, JavaScript throws a TypeError.
Choosing between match(), test(), includes(), and search()
Pick a method based on the result your code needs. Using match() just to get a yes-or-no answer creates more work than necessary. These alternatives are often clearer:
regexp.test(string)returnstrueorfalse. Use it when you only need to know whether a pattern occurs.string.includes(substring)checks for a literal substring, without regular-expression syntax. Use it for straightforward fixed-text searches.string.startsWith(prefix)andstring.endsWith(suffix)check literal text at the beginning or end.string.search(regexp)returns the index of the first match, or-1if there is none. It does not return the captures.string.matchAll(regexp)is useful when you need a sequence of all matches and their capture groups.
For example, use 'report.csv'.includes('.csv') to check for that literal substring. Use /\.csv$/i.test(filename) to check whether a filename ends in that extension regardless of case. A regular expression can express more complex rules, but a plain string method is easier to read when it is sufficient.
Common mistakes and edge cases
A frequent mistake is expecting a string argument to behave like a literal search. 'a.b'.match('.') treats the dot as a regular-expression wildcard, so it can match a character rather than a period. For literal text, use includes(). If a variable must be inserted into a regular expression as literal text, escape its regular-expression metacharacters before constructing the pattern; otherwise characters such as ., *, and ? can change the meaning.
Another trap is using g and then expecting capture groups or index on the returned array. Those details are available from a non-global match() result, but not from the array of matches returned for a global pattern. Use matchAll() if both all occurrences and their captures matter.
By default, matching is case-sensitive, so /dog/ does not match 'Dog'. Add i when case-insensitive matching is appropriate. Also remember that ^ and $ can make a pattern much stricter than an unanchored search. A test intended to find a substring may fail after anchors are added unless the entire input fits the pattern.
If you call match() without an argument, JavaScript behaves as though the pattern were an empty regular expression, which produces an empty-string match. This is rarely what application code intends, so pass an explicit pattern. Also, an empty match is not the same as no match: no match is represented by null.
Unicode, dynamic patterns, and performance
JavaScript strings use UTF-16 encoding. Some characters, including many emoji, are represented by two code units. As a result, a pattern such as /./g can treat one visible character as two matches. The u flag makes regular-expression processing more Unicode-aware for many pattern operations; for example, /./gu matches a surrogate pair as one code point. Unicode property escapes such as \p{Letter} also require Unicode-aware mode, for example /\p{Letter}+/gu.
If a pattern is built from user-provided text, distinguish carefully between text to be searched for literally and text intended to be regular-expression syntax. Constructing a regular expression from untrusted input without escaping it can produce unexpected matches or invalid patterns. Complex expressions can also take excessive time on carefully chosen input if they trigger catastrophic backtracking. Keep patterns understandable, avoid ambiguous nested repetition when possible, and limit input length when processing untrusted data.
For repeated work, it may be clearer to create a regular expression once rather than construct it inside a loop. Be cautious with global or sticky regular expressions used repeatedly with test() or exec(), because their lastIndex can affect subsequent calls. Ordinary calls to match() with a global expression begin their search from the start, but state can matter when using the regular expression methods directly.
Frequently Asked Questions
Does String.match() return a string?
No. It returns an array when it finds a match and null when it does not. The complete matching text is usually the array’s first item, available as result[0].
How do I get all matches in JavaScript?
Use a regular expression with the g flag, such as text.match(/\d+/g). This returns all complete matches, but not their capture groups. Use text.matchAll(/(\d+)/g) when you need every match together with its captures.
Why does match() return null?
The regular expression did not match anywhere in the string. Since null has no array indexes or properties, check the result before accessing result[0] or other fields.
How can I match without regard to capitalization?
Add the i flag to the regular expression, as in text.match(/hello/i). Without that flag, matching is case-sensitive.
Should I use match() or test()?
Use test() when you need only a Boolean answer. Use match() when you need the matched text or capture groups. For a fixed literal substring, includes() is often the simplest choice.
Related
- Split by Position in Power Query: A Practical Guide
- TinyTask for Sol’s RNG: What It Can and Can’t Do Safely
- Java split() Method: Split Strings with Regex and Limits
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Aggregate Functions in UPDATE: What SQL AllowsUsually, no: SQL does not allow an aggregate such as AVG() or SUM() directly as a row-level value…
- Concatenate 2 Dates in Excel: Formulas and FormattingTo concatenate two dates in Excel, convert each date to readable text with TEXT, then join the results…
- Excel LEFT Function for Dates: What It ReturnsExcel’s LEFT function can take a date, but it does not read the date as it appears on…
- Excel Difference Between Dates: Formulas and ExamplesTo find the number of days between two dates in Excel, subtract the earlier date from the later…
- COUNTIF in Excel: Count Empty Cells and Blank Cells EasilyIf your cells are in A2:A20, use =COUNTIF(A2:A20,"") to count empty cells. COUNTIF with an empty-string criterion counts…
- Excel VLOOKUP IFERROR: Return a Blank for Lookup ErrorsTo make an Excel VLOOKUP display a blank when it returns an error, wrap it in IFERROR: =IFERROR(VLOOKUP(E2,$A$2:$C$100,3,FALSE),"").…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.