javascript - 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)
推荐阅读
- python-3.x - for i in range(0,x+1) for j in range(0,y+1) for k in range(0,z+1) if((i+j+k))!=n print([[ i,j,k]])。这段代码有什么问题?
- css - 使用 CSS 或 TailwindCSS 在元素之间共享背景图像
- javascript - 当状态更改而没有突变时,Angular 会重新呈现组件列表
- python - Python函数不返回值
- sql - SQL将字符串连接为单个值
- c++ - static_cast int 引用 int?
- php - 在 Slim 中的路由之间传递数据
- mysql - 如何使用第三个表中的条件更新具有其他表中特定值的表
- javascript - js代码不工作,不显示总数
- android - 构建android源并在模拟器中闪烁