javascript - 如果捕获组等于 replace() 中的某些内容,我如何检查正则表达式替换?

标签 javascript regex

我有一个字符串,想用正则表达式替换其中的值,并根据捕获组的结果提供替换。

即,考虑这个例子:

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/

相关文章:

javascript - 如果我的 Backbone main.js 太大了怎么办?

javascript - Owl Carousel 元素绝对位置

javascript - Rails 4,完整日历,显示事件数组

javascript - jQuery 找不到自定义标签

javascript reg ex 选择每个单词的除第一个字母之外的每个字母(拉丁扩展字符)

javascript - 输入过滤器正则表达式单个小数仅允许 0 或 5

Python - 删除遵循通配符模式的字符串

javascript - "object is not a function"错误?

C++ 子模式匹配

r - 在 R 中,如何删除最后一个斜杠之前的所有内容