How Do I Replace The Last Occurance Of A Variable In A String
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, someTh
Solution 1:
The negative-lookahead would work, but so will
newText = newText.replace(new RegExp("(.*)" + foo), "$1somethingElse");
Solution 2:
Do a negative lookahead to make the match fail if there's another occurrence of the needle
functionreplaceLast(haystack, needle, replacement) {
// you may want to escape needle for the RegExpvar re = newRegExp(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"
Post a Comment for "How Do I Replace The Last Occurance Of A Variable In A String"