How do I replace the last occurrence of a variable(foo) in a string with "foo"?
I've tried:
var re = new RegExp(".*" + (foo)));
var newText = currentText.replace(re, someThingElse);
How do I replace the last occurrence of a variable(foo) in a string with "foo"?
I've tried:
var re = new RegExp(".*" + (foo)));
var newText = currentText.replace(re, someThingElse);
The negative-lookahead would work, but so will
newText = newText.replace(new RegExp("(.*)" + foo), "$1somethingElse");
Do a negative lookahead to make the match fail if there's another occurrence of the needle
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 the replacement is exactly what you expect, i.e. you can use $1
, $2
, etc as normal, and similarly if you pass in a function the parameters will be what you expect too
replaceLast('bar foobar baz', '(b)(a)(r)', '$3$2$1'); // "bar foorab baz"