这是一个想法......
这是一个区分大小写的字符串搜索版本
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。我正在做,所以我会尽快发布)
更新:这是一个不区分大小写的字符串搜索版本
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
注意上面的代码寻找一个字符串。不是整个单词(即 RegEx 中的单词边界)。如果字符串必须是一个完整的单词,则必须对其进行修改。
更新 2:这是一个不区分大小写的正则表达式全词匹配版本
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
祝你好运
:)