我有以下代码:
var txt = 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
txt += 'DELIMETER is replaced'; <-- leave this and not replace the last DELIMETER
txt = txt.replace(/DELIMETER/g, "HI");
我知道所有带有“ DELIMETER”的单词都将被替换为“ HI”,但是我想要的只是替换前四个出现的“ DELIMETER”,而保留最后一个“ DELIMETER”而不替换该单词。
我必须使用正则表达式如何实现?
首先将文本分为两部分,最后一个定界符之前的部分,以及后面的所有内容。然后在第一部分中进行替换,并将它们连接在一起。
var txt = 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
var match = txt.match(/(.*)(DELIMETER.*)/);
if (match) {
var [whole, part1, part2] = match;
part1 = part1.replace(/DELIMETER/g, 'OK');
txt = part1 + part2;
}
console.log(txt);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句