3 回答
TA贡献1875条经验 获得超5个赞
您可以混合使用正则表达式和 java 脚本。一种这样的方法是通过使用字符串,然后使用函数在替换时循环访问匹配项来检查它是否是最后一次出现。如果匹配项位于末尾,则返回匹配的字符串(定界符),否则,请替换为替换项 (HI)。lastIndexOf
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)
TA贡献1775条经验 获得超11个赞
首先将文本分成两部分,最后一个分隔符之前的部分和它之后的所有内容。然后在第一部分中进行替换,并将它们连接在一起。
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);
TA贡献1873条经验 获得超9个赞
只需提前切掉最后一个分隔符即可。
var matches = txt.match(/^(.*)(DELIMETER.*)$/) txt = matches[1].replace(/DELIMETER/g, "HI") + matches[2]
添加回答
举报