user1652427
user1652427

Reputation: 697

How can I actually capture things between curly braces in JavaScript?

I need to capture everything between curly brackets. So if I have the string:

{this} {is a} blah {test}

should return [this, is a, test].

My code looks like this:

var myString = "{this} {is a} blah {test}";
var parts = (/{([^{}]+)}/g).exec(myString);

//   parts = [{this}, {is a}, {test}]  


var parts = (/{([^{}]+)}/g).exec(myString);
//   parts = [{this}, this]

Any ideas/help?

Upvotes: 0

Views: 133

Answers (2)

Brian Cray
Brian Cray

Reputation: 1275

var parts = myString.match(/{[^}]+/g).map(function (s) { return s.slice(1); });

Upvotes: -2

T.J. Crowder
T.J. Crowder

Reputation: 1074969

I think you're over-egging the pudding:

var rex = /\{([^}]+)\}/g;
var str = "{this} {is a} blah {test}";
var m;
for (m = rex.exec(str); m; m = rex.exec(str)) {
    console.log(m[1]);
}

Live Example | Source

Upvotes: 7

Related Questions