我有一个字符串,想用正则表达式替换其中的值,并根据捕获组的结果提供替换。
即,考虑这个例子:
var thing = "thing 1";
var result = thing.replace(/\w+ (\d+)/g,"$1");
在这种情况下,结果是1
,因为替换采用捕获组1的匹配。现在我想比较第一个捕获组的结果与1
并替换为 the first
,如果它是 1
,否则替换为 a
。在伪代码中,像这样:
var thing = "thing 1";
var result = thing.replace(/\w+ (\d+)/g,"$1" == "1" ? "the first" : "a");
我该怎么做?
请注意,我提供的代码只是一个示例(因此请不要建议按空格拆分和获取数字等内容),我希望该解决方案适用于更复杂的正则表达式。
最佳答案
使用String#replace
回调:
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);
关于javascript - 如果捕获组等于 replace() 中的某些内容,我如何检查正则表达式替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34528265/