Regular Expression to get a string between parentheses in JavaScript
To fetch text between parentheses, employ this regex pattern /\(([^)]+)\)/
in JavaScript:
Using [^)]+
, we match a string of characters excluding the closing parenthesis. The chained optional expression ?.[1]
ensures no errors surface if there's no match, and null
is returned instead.
Breaking the pattern
In the regex /\(([^)]+)\)/
:
\( and \)
: Match real parentheses in the text. In regex,(
and)
are special characters.([^)]+)
: This is a capturing group, capturing one or more characters that are not a closing parenthesis.
Dealing with more complex cases
Handling multiple groups
If you need to deal with multiple occurrences, add the g
(global) flag into your regex:
Dealing with nested parentheses
For nested parentheses, the basic pattern we used won't work correctly. As JavaScript’s regex doesn't support recursive patterns, you could use a complicated regex that balances parentheses, but it’s often easier to iterate over the string or use a parser.
Alternative: string manipulation
If you're all about speed, then split
could be a tempting alternative to regex:
However, keep in mind that regex gives you more flexibility especially when dealing with more complex string structures.
Handy tips and tricks
Pairing Global with matchAll
Make use of matchAll
with regex g
flag to extract multiple occurrences:
Null matches? No problem!
Always check for null matches to prevent messy runtime errors:
Understanding capturing groups
In the regex /\(([^)]+)\)/
, group 1 (([^)]+)
) captures the text you are interested in. Aim for the bullseye. 🎯
Test your regex
Utilize online realtime regex testers like regex101 for a comprehensive breakdown of your regex.
Was this article helpful?