简体   繁体   中英

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?

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);

您可以使用String.match()

var array = str.match(regex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM