Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  12] [ 1]  / answers: 1 / hits: 29591  / 10 Years ago, thu, april 17, 2014, 12:00:00

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



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?


More From » regex

 Answers
88

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)



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.



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
:)


[#71414] Wednesday, April 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kourtney

Total Points: 368
Total Questions: 103
Total Answers: 85

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
kourtney questions
Sun, Oct 4, 20, 00:00, 4 Years ago
Tue, Oct 29, 19, 00:00, 5 Years ago
Thu, Apr 4, 19, 00:00, 5 Years ago
Fri, Mar 1, 19, 00:00, 5 Years ago
;