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]
添加回答
舉報
