Sometimes, we may want to get the substrings in a JavaScript string that is between parentheses.
In this article, we'll look at how to use regular expressions to get strings between parentheses with JavaScript.
Use Regular Expression to Get Strings Between Parentheses with JavaScript
We can use the match method to get the substrings in a string that match the given regex pattern.
For instance, we can write:
const txt = "I expect five hundred dollars ($500). and new brackets ($600)";
const regExp = /\(([^)]+)\)/g;
const matches = [...txt.match(regExp)];
console.log(matches)
We create the regExp regex that matches anything between parentheses.
The g flag indicates we search for all substrings that match the given pattern.
Then we call match with the regExp to return an array of strings that are between the parentheses in txt .
Therefore, matches is [“($500)”, “($600)”] .
We can also exclude strings with inner parentheses with:
/\(([^()]*)\)/g
With the matchAll method, we can also get the substrings that are inside the parentheses without the parentheses.
To use it, we write:
const txt = "I expect five hundred dollars ($500). and new brackets ($600)";
const regExp = /\(([^)]+)\)/g;
const matches = [...txt.matchAll(regExp)].flat();
console.log(matches)
We call flat to flatten the array.
And so matches is [“($500)”, “$500”, “($600)”, “$600”] .
Conclusion
We can use regular expressions to get strings between parentheses with JavaScript.