Languages

JavaScript - RegEx to match text between parentheses

0 points
Asked by:
Aston-Freeman
787

I have the following string:

var text = 'some_text/([0-9])/([a-z])';

and I want to use a regular expression to match everything between the parentheses and get an array of matches like the one below:

[[0-9], [a-z]]
1 answer
0 points
Answered by:
Aston-Freeman
787

Use the following regex: /\(([^()]+)\)/g.

Practical example:

// ONLINE-RUNNER:browser;

var text = 'text/([0-9])/([a-z])';
var regex = /\(([^()]+)\)/g;

var result = text.match(regex);

if (result) {
    console.log(result[0]); // ([0-9])
    console.log(result[1]); // ([a-z])
}

You can also remove the wrapping parentheses using:

console.log(result[0].substring(1, result[0].length - 1)); // [0-9]
console.log(result[1].substring(1, result[1].length - 1)); // [a-z]
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join