anoopelias
anoopelias

Reputation: 9548

JavaScript - extract using regex group

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

Answers (2)

r0dney
r0dney

Reputation: 745

You can use String.match()

var array = str.match(regex);

Upvotes: 1

Niels
Niels

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

Related Questions