JavaScript: replace last occurrence of text in a string JavaScript: replace last occurrence of text in a string javascript javascript

JavaScript: replace last occurrence of text in a string


Well, if the string really ends with the pattern, you could do this:

str = str.replace(new RegExp(list[i] + '$'), 'finish');


You can use String#lastIndexOf to find the last occurrence of the word, and then String#substring and concatenation to build the replacement string.

n = str.lastIndexOf(list[i]);if (n >= 0 && n + list[i].length >= str.length) {    str = str.substring(0, n) + "finish";}

...or along those lines.


I know this is silly, but I'm feeling creative this morning:

'one two, one three, one four, one'.split(' ') // array: ["one", "two,", "one", "three,", "one", "four,", "one"].reverse() // array: ["one", "four,", "one", "three,", "one", "two,", "one"].join(' ') // string: "one four, one three, one two, one".replace(/one/, 'finish') // string: "finish four, one three, one two, one".split(' ') // array: ["finish", "four,", "one", "three,", "one", "two,", "one"].reverse() // array: ["one", "two,", "one", "three,", "one", "four,", "finish"].join(' '); // final string: "one two, one three, one four, finish"

So really, all you'd need to do is add this function to the String prototype:

String.prototype.replaceLast = function (what, replacement) {    return this.split(' ').reverse().join(' ').replace(new RegExp(what), replacement).split(' ').reverse().join(' ');};

Then run it like so:str = str.replaceLast('one', 'finish');

One limitation you should know is that, since the function is splitting by space, you probably can't find/replace anything with a space.

Actually, now that I think of it, you could get around the 'space' problem by splitting with an empty token.

String.prototype.reverse = function () {    return this.split('').reverse().join('');};String.prototype.replaceLast = function (what, replacement) {    return this.reverse().replace(new RegExp(what.reverse()), replacement.reverse()).reverse();};str = str.replaceLast('one', 'finish');