Javascript regex return text between parenthesis without the parenthesis

str= "I'm gonna be (500 miles) (200  miles) (300 miles)";

console.log(str.match(/\((.*?)\)/g)) 

// outputs array of [(500 miles), (200 miles), (300 miles)]

Hi,

The above code returns what’s between parenthesis.

But, how can I get the output without the parenthesis?

Eg:[500 miles, 200 miles, 300 miles]

Right now it outputs all matches with parenthesis.

Hi @Nordy, to match anything inside following / preceeding certain characters but without those characters you can use lookbehind / lookahead assertions respectively:

console.log(str.match(/(?<=\()(.*?)(?=\))/g))

Another option would be using matchAll(), which will also give you the matches of the capturing parentheses… if you want to support IE though you’ll have to repeatedly call exec() instead, which is basically what matchAll() does.

1 Like

Thanks for your reply. This works only in Chrome I guess? Firefox and other Browsers throw an error.

Ah yes it seems the lookahead assertion is indeed not that widely supported yet… matchAll() is however supported in FF as well:

const str = "I'm gonna be (500 miles) (200  miles) (300 miles)"
const matches = Array.from(str.matchAll(/\((.*?)\)/g), match => match[1])

console.log(matches)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.