Explain Codes LogoExplain Codes Logo

Regular Expression to get a string between parentheses in JavaScript

javascript
regex
string-manipulation
javascript-features
Anton ShumikhinbyAnton Shumikhin·Nov 18, 2024
TLDR

To fetch text between parentheses, employ this regex pattern /\(([^)]+)\)/ in JavaScript:

const result = "Sample (desired text)".match(/\(([^)]+)\)/)?.[1] || null; console.log(result); // "desired text", as easy as a Sunday morning

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:

const matches = [..."Sample (first) Sample (second)".matchAll(/\(([^)]+)\)/g)]; matches.forEach(match => console.log(match[1])); // Logs: // "first" // "second"

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:

const str = "Sample (text you need)"; const beforeParentheses = str.split('(')[1] || ""; // split at opening parenthesis const result = beforeParentheses.split(')')[0] || null; // split the subsequent string at closing parenthesis console.log(result); // "text you need" - Ninja way of decoding

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:

const regex = /\(([^)]+)\)/g; const string = "Many (pearls) are hidden in the (ocean) depths."; const matchesIterator = string.matchAll(regex); for (const match of matchesIterator) { console.log(match[1]); // It's time to go pearl diving }

Null matches? No problem!

Always check for null matches to prevent messy runtime errors:

const match = "No parentheses here".match(/\(([^)]+)\)/); const result = match ? match[1] : null;

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.