1

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?

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use String.match()

var array = str.match(regex);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.