在javascript中替换最后出现的单词 [英] Replace last occurrence word in javascript
问题描述
我在替换JS中的最后一个单词时遇到问题,我仍在搜索解决方案,但我无法得到它。
I have a problem with replacing last word in JS, I am still searching solution but i cannot get it.
我有这段代码:
var string = $(element).html(); // "abc def abc xyz"
var word = "abc";
var newWord = "test";
var newV = string.replace(new RegExp(word,'m'), newWord);
我想在此字符串中替换最后一个单词abc,但现在我只能替换所有或第一个在字符串中出现。我怎样才能做到这一点?也许不是好方法?
I want replace last word "abc" in this string, but now I can only replace all or first occurrence in string. How can I do this? Maybe is not good way?
推荐答案
这是一个想法....
Here is an idea ....
这是一个区分大小写的字符串搜索版本
This is a case-sensitive string search version
var str = 'abc def abc xyz';
var word = 'abc';
var newWord = 'test';
// find the index of last time word was used
// please note lastIndexOf() is case sensitive
var n = str.lastIndexOf(word);
// slice the string in 2, one from the start to the lastIndexOf
// and then replace the word in the rest
str = str.slice(0, n) + str.slice(n).replace(word, newWord);
// result abc def test xyz
如果你想要一个不区分大小写的版本,那么代码必须改变。让我知道,我可以为你改变它。 (PS。我这样做,所以我会很快发布)
If you want a case-insensitive version, then the code has to be altered. Let me know and I can alter it for you. (PS. I am doing it so I will post it shortly)
更新:这是一个不区分大小写的字符串搜索版本
Update: Here is a case-insensitive string search version
var str = 'abc def AbC xyz';
var word = 'abc';
var newWord = 'test';
// find the index of last time word was used
var n = str.toLowerCase().lastIndexOf(word.toLowerCase());
// slice the string in 2, one from the start to the lastIndexOf
// and then replace the word in the rest
var pat = new RegExp(word, 'i')
str = str.slice(0, n) + str.slice(n).replace(pat, newWord);
// result abc def test xyz
NB 以上代码寻找一个字符串。不是整个单词(即RegEx中的单词边界)。如果字符串必须是一个完整的单词,那么它必须重做。
N.B. Above codes looks for a string. not whole word (ie with word boundaries in RegEx). If the string has to be a whole word, then it has to be reworked.
更新2:这是一个不区分大小写的整个单词与RegEx匹配版本
Update 2: Here is a case-insensitive whole word match version with RegEx
var str = 'abc def AbC abcde xyz';
var word = 'abc';
var newWord = 'test';
var pat = new RegExp('(\\b' + word + '\\b)(?!.*\\b\\1\\b)', 'i');
str = str.replace(pat, newWord);
// result abc def test abcde xyz
祝你好运
:)
Good luck :)
这篇关于在javascript中替换最后出现的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!