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

我知道所有有“定界仪”的单词都将替换为“HI”,但我想要的只是替换“定界仪”的前四个出现,但保留最后一个“定界仪”,而不是替换该词。


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




RISEBY
浏览 121回答 3
3回答

慕田峪4524236

您可以混合使用正则表达式和 java 脚本。一种这样的方法是通过使用字符串,然后使用函数在替换时循环访问匹配项来检查它是否是最后一次出现。如果匹配项位于末尾,则返回匹配的字符串(定界符),否则,请替换为替换项 (HI)。lastIndexOfvar 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) {&nbsp; var [whole, part1, part2] = match;&nbsp; part1 = part1.replace(/DELIMETER/g, 'OK');&nbsp; txt = part1 + part2;}console.log(txt);

眼眸繁星

只需提前切掉最后一个分隔符即可。var&nbsp;matches&nbsp;=&nbsp;txt.match(/^(.*)(DELIMETER.*)$/) txt&nbsp;=&nbsp;matches[1].replace(/DELIMETER/g,&nbsp;"HI")&nbsp;+&nbsp;matches[2]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript