JavaScript:替换字符串中最后出现的文本 [英] JavaScript: replace last occurrence of text in a string

查看:106
本文介绍了JavaScript:替换字符串中最后出现的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅下面的代码段:

var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
     if (str.endsWith(list[i])
     {
         str = str.replace(list[i], 'finish')
     }
 }

我想用字符串中的单词finish替换单词one的最后一个匹配项,我所拥有的将不起作用,因为replace方法只会替换它的第一次出现。有谁知道我怎么能修改那个片段所以它只替换'one'的最后一个实例

I want to replace the last occurrence of the word one with the word finish in the string, what I have will not work because the replace method will only replace the first occurrence of it. Does anyone know how I can amend that snippet so that it only replaces the last instance of 'one'

推荐答案

好吧,如果字符串真的以模式结束,你可以这样做:

Well, if the string really ends with the pattern, you could do this:

str = str.replace(new RegExp(list[i] + '$'), 'finish');

这篇关于JavaScript:替换字符串中最后出现的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆