我试图使用RegExp
和String.replace
来替换空格分隔字符串中单词的第二次出现。
我不明白为什么我的代码不起作用。我在正确的匹配周围有括号,那么为什么它要替换整个RegExp
的匹配,而不是只替换捕获组中的匹配呢?
const re = /(\w+) \w+$/;
const string = 'john deer senior third';
const result = string.replace(re, match => `[${match}]`);
console.log(result); // john deer [senior third]
预期结果:
john deer [senior] third
发布于 2020-07-22 01:19:40
有关替换函数在MDN中的签名,请参见String.prototype.replace
。第一个参数是完全匹配,捕获组随后出现。
另外,replace
将取代完全匹配,而不仅仅是第一个捕获组(一个正则表达式中也可以有多个捕获组)。为了缓解这一问题,您可以使用前瞻性,或者将后半段连接回:
let a = 'john deer senior third'.replace(/\w+(?= \w+$)/, m => `[${m}]`);
let b = 'john deer senior third'.replace(/(\w+)( \w+)$/, (_, a, b) => `[${a}]${b}`);
console.log(a);
console.log(b);
也许还有更优雅的方法来做到这一点。
https://stackoverflow.com/questions/63025167
复制相似问题