I know this is stupid, but today I feel creative:
'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, all you have 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 this: str = str.replaceLast('one', 'finish');
One limitation you should know is that since the function is separated by a space, you probably cannot find / replace anything with a space.
Actually, now that I’m thinking about this, you can get around the problem of “space” by dividing it into 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');