code-guy
code-guy

Reputation: 31

How to extract text between round brackets?

I would like to extract the text within () brackets. The string looks like this: It is within the

Some text: 5 (some numbers) + some more numbers
asdfkjhsd: 7 (6578) + 57842
djksbcuejk: 4 (421) + 354

My javascript looks like this:

var fspno = document.getElementsByTagName("td")[142].innerText;
var allfsp = fspno.match();

I want this script to collect all numbers within the brackets in an array. I used

fspno.match(/\((.*?)\)/g);

but it returned with the brackets. I want only the text inside the brackets. Any help would be appreciated. Thanks.

Upvotes: 1

Views: 854

Answers (4)

Plynx
Plynx

Reputation: 11461

The easiest way is to turn off the g option and get the [1] index on the match, e.g.:

fspno.match(/\((.*?)\)/)[1];

But that will return an error if nothing is found, so if you don't know if you'll have a parenthesized part or not, or you can use this idiom:

(fspno.match(/\((.*?)\)/) || [,""])[1];

which will return "" if it can't find a match.

If you know you need the g option (i.e. there might be more than one thing in parentheses and you want them all) you can use:

var match, matches=[]; while (match = /\((.*?)\)/g.exec(s)) matches.push(match[1]);
// matches is now an array of all your matches (without parentheses)

Upvotes: 0

georg
georg

Reputation: 214949

There's no way in javascript to extract all matches with all groups at once, therefore you either have to use exec in a loop:

re = /\((.+?)\)/g
found = []
while(r = re.exec(fspno))
    found.push(r[1])

or abuse String.replace to collect the matches:

re = /\((.+?)\)/g
found = []
fspno.replace(re, function($0, $1) { found.push($1)})

In your particular case, however, it's possible to rewrite the expression so that it doesn't contain groups and can be used with String.match:

re = /[^()]+(?=\))/g
found = fspno.match(re)

Upvotes: 1

SachinGutte
SachinGutte

Reputation: 7055

You might not need g option. fiddle here

or

var fspno = "7 (6578) + 57842";
var found = fspno.match(/\((.*?)\)/);

if (found) {
    var found1 = found[1];
    alert(found1);
}

Upvotes: 0

Rok Kralj
Rok Kralj

Reputation: 48725

/\((.*?)\)/.exec( '7 (6578) + 57842' )[1]

Upvotes: 0

Related Questions