Do a negative so the match doesn’t work if there is another needle appearance
function replaceLast(haystack, needle, replacement) { // you may want to escape needle for the RegExp var re = new RegExp(needle + '(?![\\s\\S]*?' + needle + ')'); return haystack.replace(re, replacement); } replaceLast('foobarfoo', 'foo', 'baz'); // "foobarbaz" replaceLast('foobarfoo \n foobarfoo', 'foo', 'baz'); // "foobarfoo \n foobarbaz" replaceLast('foo ', 'foo', 'baz'); // "baz "
The advantage of this method is that a replacement is exactly what you expect, i.e. you can use $1 , $2 , etc. as usual, and similarly, if you pass a function, the parameters will be what you expect
replaceLast('bar foobar baz', '(b)(a)(r)', '$3$2$1'); // "bar foorab baz"
Paul S. Mar 21 '15 at 21:49 2015-03-21 21:49
source share