How do you access the matched groups in a JavaScript regular expression?
Access regex groups using the .exec()
or .match()
methods as shown below:
Here firstWord
equals "Hello"
, and secondWord
equals "World"
. Use parentheses ()
in your pattern to create capture groups.
Working with multiple matches: Meet matchAll
When your string contains multiple, repeating patterns, String.prototype.matchAll()
is invaluable. It returns an iterator for all matches, which you can easily turn into an array using spread syntax:
Remember, index 1 onwards contains your capturing groups.
Utilising capture groups: Tips and tricks
The power of matchAll
matchAll
is a Swiss Army knife. It does the job neatly and handles side effects on the regex
's lastIndex
property, which is altered when the regex is executed with a "g" flag.
Remember, always use the global flag g
to prevent the infinite loop that matchAll
may cause!
Replace
meets capturing groups
The replace()
method with a callback function is an alternative way to work with capture groups. It's like inviting a friend to help.
This might not replace the initial string but it sure does replace your worries with match capturing!
Handling no matches with match
JavaScript can get dramatic and return null
for no matches. Here's a way to keep it under control:
Advanced group matching techniques
Non-capturing groups and word boundaries
Non-capturing groups (?:...)
and word boundaries \b
can polish your regex skills to wow even the most seasoned developers.
Remember, non-capturing groups organize your pattern but don't return captured groups.
Cleaner manipulation with arrow functions
Manipulating matches gets prettier with ES6 arrow functions:
Ain't that a classy way to convert all words to uppercase!
Replace
to the extraction rescue
Was this article helpful?