search
String.prototype.match
Runs a regular expression against the string and returns match information. With the g flag it returns an array of all match strings; without it, an exec-style array with capture groups, index, and input (or null).
str.match(regexp) Parameters
| Parameter | Purpose |
|---|---|
| regexp | RegExp to match; a non-RegExp is passed to new RegExp() |
| returns | Array of matches (or capture array) when found; null otherwise |
Examples
console.log('hello 123 world 456'.match(/\d+/g)); Prints [ '123', '456' ]
console.log('hello 123'.match(/(\w+)\s(\d+)/)[2]); Prints '123' (second capture group)
console.log('abc'.match(/z/)); Prints null
console.log('hello'.match(/l/)); Prints [ 'l', index: 2, input: 'hello', groups: undefined ]
Gotcha
Return shape depends on the g flag — an easy source of bugs. Returns null (not []) when nothing matches, so guard before iterating.
Related methods
String.prototype.matchAll
Returns an iterator of all detailed match results, each including capture groups, index, and input. Added in ES2020 and requires a global (g) RegExp — non-global patterns throw TypeError.
String.prototype.replace
Returns a new string with the first match of pattern replaced. Pattern can be a string (only the first occurrence) or a RegExp (all occurrences when the g flag is set).
String.prototype.indexOf
Returns the index of the first occurrence of searchValue within the string, or -1 if not found. Search is case-sensitive and starts from fromIndex (default 0).
String.prototype.includes
Returns true if searchString appears anywhere in the string, otherwise false. Added in ES2015 as a cleaner boolean alternative to indexOf() !== -1.
String.prototype.startsWith
Returns true if the string begins with searchString at the given position (default 0). Added in ES2015 and is more efficient than slice() + === comparisons.