首页 > 解决方案 > 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

解决方案


您可以混合使用正则表达式和 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)


推荐阅读