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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23136691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:24:20  来源:igfitidea点击:

Replace last occurrence word in javascript

javascriptregexreplace

提问by Beniamin

I have a problem with replacing last word in JS, I am still searching solution but i cannot get it.

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

I have this code:

我有这个代码:

var string = $(element).html(); // "abc def abc xyz"
var word   = "abc";
var newWord = "test";

var newV   = string.replace(new RegExp(word,'m'), newWord);

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?

我想替换这个字符串中的最后一个单词“abc”,但现在我只能替换字符串中的所有或第一次出现。我怎样才能做到这一点?也许不是好方法?

回答by erosman

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

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)

如果您想要不区分大小写的版本,则必须更改代码。让我知道,我可以为你改变它。(PS。我正在做,所以我很快就会发布)

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

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.

注意上面的代码寻找一个字符串。不是整个单词(即在 RegEx 中有单词边界)。如果字符串必须是一个完整的单词,则必须对其进行重新设计。

Update 2:Here is a case-insensitive whole word match version with 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

Good luck :)

祝你好运 :)

回答by bobthedeveloper

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

回答by anubhava

You can use lookahead to get last word in a sentence:

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

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

回答by Robin

You want to both:

你想要:

  • match abc
  • check that there isn't another abcafterward in the string
  • 比赛 abc
  • 检查abc字符串中是否没有另一个

So you can use:

所以你可以使用:

abc(?!.*abc)

(?!...)is a negative lookahead, it will fail the whole regex match if what's inside the lookahead is matched.

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

Also be careful as this would match abcin abcdaire: if you only want abcas a separate word you need to add word boundaries \b:

另外要小心,因为这将匹配abcabcdaire:如果你只是想abc你需要添加单词边界的独立的字\b

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

回答by sshashank124

I'm not too familiar with JavaScript but you can probably twist this to fit your needs:

我对 JavaScript 不太熟悉,但您可以根据自己的需要进行修改:

(\b\w+\b)(.*)(\1)replace with \1\2+'your_key_word'

(\b\w+\b)(.*)(\1)用。。。来代替 \1\2+'your_key_word'

See the demoto see what I mean.

请参阅演示以了解我的意思。

回答by webduvet

try

尝试

var string = $(element).html(); // "abc def abc xyz"
var word   = "abc";
var newWord = "test";

var newV   = string.replace(new RegExp(word+'$'), newWord);

回答by tewathia

You can use the fact that the replacemethod replaces only the first occurrence of the target string if used without the global flag, and try something like:

replace如果在没有全局标志的情况下使用该方法,您可以使用该方法仅替换目标字符串的第一次出现的事实,并尝试以下操作:

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

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