nicael
nicael

Reputation: 18995

How do I check in the regex substitution if capture group is equal to something in replace()?

I have a string and want to replace the values in it with regex and provide the substitution basing on the result of the capture group.

I.e., consider this example:

var thing = "thing 1";
var result = thing.replace(/\w+ (\d+)/g,"$1");

In this case, the result is 1, because the substitution takes the match of the capture group 1. Now I want to compare the result of the first capture group with 1 and substitute with the first, if it's 1, otherwise with a. In pseudocode, like this:

var thing = "thing 1";
var result = thing.replace(/\w+ (\d+)/g,"$1" == "1" ? "the first" : "a");

How would I go about it?

Note that the code I've provided is just an example (so please don't suggest something like splitting by space and getting the number, or etc), and I want the solution to work with more complex regexes.

Upvotes: 1

Views: 101

Answers (1)

Tushar
Tushar

Reputation: 87203

Use String#replace callback:

thing.replace(/\w+ (\d+)/g, function (completeMatch, firstCapturedGroup) {
    return firstCapturedGroup == "1" ? "the first" : "a";
});

var thing = "thing 1";
var result = thing.replace(/\w+ (\d+)/g, function(e, firstCapturedGroup) {
  return firstCapturedGroup == "1" ? "the first" : "a";
});
document.write(result);

Upvotes: 2

Related Questions