Reputation: 121
I'm looking for a way to get the value from a second pair of brackets.
this is an example : var foo = "bar - (cocktails) - (drunk);
Now I need the value "drunk", but not the value "cocktails".
I managed to get the value from the first pair, but still struggling to get the data from the second pair.
This is my code to extract the first value :
var foo = "bar - (cocktails) - (drunk)";
chosenfoo = foo;
filterOut = /\((.*)\)/i;
var strippedFoo= chosenfoo.match(filterOut)[1];
$('#foobarfield').val(strippedFoo);
I was too brave to think that changing the number 1 to 2 would solve it. :)
When the value would be "bar - (cocktails)" then I'll get it right, like "cocktails", but with the previously given var with both pairs of brackets the result value for this code is :
cocktails) - (drunk
not exactly what I want :(
anyone can help me on this one?
Upvotes: 0
Views: 77
Reputation: 119
Look at below example
var foo = "bar - (cocktails) - (drunk)";
var strippedFoo= foo.match(/\((.*?)\)/gi)[1].replace(/\(|\)/g, "");;
alert(strippedFoo)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 3573
You can get the last bracket with this:
\((?!.*\().*\)
And with this one you can get the last complete bracket even if there is a non-complete bracket (just one (
or )
) at the end:
\((?!.*\(.*\)).*?\)
Update to match the content of brackets:
\((?!.*\(.*\))(.*?)\)
Upvotes: 0
Reputation: 28611
You can get what you want with two changes:
/g
for global matches (multiple matches) otherwise it stops on first match?
to mean (basically) 'shortest match possible'As in:
/\((.*?)\)/gi
With the change to /g, the return is an array of matches, so first is [0]
and second [1]
Snippet:
var foo = "bar - (cocktails) - (drunk)";
chosenfoo = foo;
filterOut = /\((.*?)\)/gi;
var strippedFoo= chosenfoo.match(filterOut)[1];
$('#foobarfield').text(strippedFoo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='foobarfield'></div>
Upvotes: 1
Reputation: 477
you are matching everything between the 1st and the very last parenthesis. fix your regex like this
/\((.*?)\)/gi
and you should end up with 2 captures
Upvotes: 0