Javascript - 替换除最后一个分隔符之外的所有分隔符



我有这个代码:

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"而不替换该单词。

我必须使用正则表达式如何实现这一点?

你可以混合使用正则表达式和javascript。一种这样的方法是通过使用字符串的lastIndexOf然后使用函数在替换时遍历匹配来检查它是否是最后一次出现。如果匹配项位于末尾,则返回匹配的字符串 (DELIMETER(,否则,替换为替换字符串 (HI(。

var txt = 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
txt += 'DELIMETER is replaced';
const target = "DELIMETER";
const replacement = "HI"
const regex = new RegExp(target, 'g');
txt = txt.replace(regex, (match, index) => index === txt.lastIndexOf(target) ? match : replacement);
console.log(txt)

首先将文本分成两部分,最后一个分隔符之前的部分,以及它之后的所有部分。然后在第一部分中进行替换,并将它们连接在一起。

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);

只需提前剪掉最后一个分隔符即可。

var matches = txt.match(/^(.*)(DELIMETER.*)$/)
txt = matches[1].replace(/DELIMETER/g, "HI") + matches[2]

最新更新