替换javascript中最后一个出现的单词

Replace last occurrence word in javascript

本文关键字:单词 最后一个 javascript 替换      更新时间:2023-09-26

我在JS中替换最后一个单词时遇到问题,我仍在搜索解决方案,但无法获得。

我有这个代码:

var string = $(element).html(); // "abc def abc xyz"
var word   = "abc";
var newWord = "test";
var newV   = string.replace(new RegExp(word,'m'), newWord);

我想替换这个字符串中的最后一个单词"abc",但现在我只能替换字符串中所有或第一个出现的单词。我该怎么做?也许这不是一个好办法?

这里有一个想法。。。。

这是一个区分大小写的字符串搜索版本

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

N。B.以上代码查找字符串。不是整个单词(RegEx中有单词边界)。如果字符串必须是一个完整的单词,那么它必须被重新处理。

更新2:这是一个带有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

祝你好运:)

// create array
var words = $(element).html().split(" ");
// find last word and replace it
words[words.lastIndexOf("abc")] = newWord 
// put it back together
words = words.join(" ");

您可以使用lookahead来获取句子中的最后一个单词:

var string = "abc def abc xyz";
var repl = string.replace(/'babc'b(?!.*?'babc'b)/, "test");
//=> "abc def test xyz"

您想要两者:

  • 匹配abc
  • 检查字符串中之后是否没有其他abc

所以你可以使用:

abc(?!.*abc)

(?!...)是一个负前瞻,如果前瞻中的内容匹配,它将使整个正则表达式匹配失败。

还要小心,因为这将与abcdaire中的abc匹配:如果你只想将abc作为一个单独的单词,你需要添加单词边界'b:

'babc'b(?!.*'babc'b)

我对JavaScript不太熟悉,但您可能会根据自己的需求进行调整:

('b'w+'b)(.*)('1)替换为'1'2+'your_key_word'

看演示,了解我的意思。

尝试

var string = $(element).html(); // "abc def abc xyz"
var word   = "abc";
var newWord = "test";
var newV   = string.replace(new RegExp(word+'$'), newWord);

如果不使用全局标志,则可以使用replace方法仅替换目标字符串的第一个出现,并尝试以下操作:

"abc def abc xyz abc jkl".split(' ').reverse().join(' ').replace('abc', 'test').split(' ').reverse().join(' ')