Reputation: 9548
Is it possible to extract a regex group value pattern of a string?
For example, the following code gives
var str = "alpha bravo charlie delta";
var regex = /\s(\w+)\s(\w+)/
var value = str.replace(regex, "$1_$2"); // Gives alphabravo_charlie delta
What I am looking for is something like,
var value = str.extract(regex, "$1_$2"); // Which should give bravo_charlie
While str.extract
doesn't exist, is there any other way I can get same results?
Upvotes: 1
Views: 3304
Reputation: 49919
You can do this:
var str = "alpha bravo charlie delta";
var regex = /\s(\w+)\s(\w+)/;
var value = "";
str.replace(regex, function($0, $1, $2){
value = $1 + "_" + $2;
});
alert(value);
Upvotes: 4