Sławosz
Sławosz

Reputation: 11687

Simple javascript string extraction

I have such string:

"{{foo}} is {{bar}}"

I would like to extract values from {{}}, how I can achieve this? Expected result is

["foo", "bar"]

I tried

"{{foo}} is {{bar}}".match(/\{\{(.*?)\}\}/g)

But its not working as I expected.

Upvotes: 2

Views: 71

Answers (4)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 19007

Try this

var arr = [];
var str = "{{foo}} is {{bar}}"
str.replace(/{{(.*?)}}/g, function(s, match) {
                           arr.push(match);
                        });

document.write('<pre>'+JSON.stringify(arr));

Upvotes: 0

georg
georg

Reputation: 215009

In JS, match with g only returns top-level matches, no groups. You can map the string as @gurvinder372 suggested:

res = "{{foo}} is {{bar}}".match(/{{.*?}}/g).map(s => s.slice(2, -2));

document.write('<pre>'+JSON.stringify(res,0,3));

or use .replace to populate the array:

res = [];

"{{foo}} is {{bar}}".replace(/{{(.*?)}}/g, (_, $1) => res.push($1));


document.write('<pre>'+JSON.stringify(res,0,3));

Note that there's no need to escape curly braces in your regex.

Upvotes: 1

anubhava
anubhava

Reputation: 785541

You should use exec in a loop like this to grab capturing groups with global flag in JS:

var m;
var re = /\{\{(.*?)\}\}/g
var str = "{{foo}} is {{bar}}"
var matches = [];

while((m=re.exec(str)) != null) {
   matches.push(m[1]);
}

console.log(matches);
//=> ["foo", "bar"]

Upvotes: 4

gurvinder372
gurvinder372

Reputation: 68413

Regex is fine, just use map to strip the braces

    var output = "{{foo}} is {{bar}}".match(/\{\{(.*?)\}\}/g).map(function(value){ return value.substring(2,value.length-2)  });
    document.body.innerHTML += output;

Upvotes: 1

Related Questions