How to replace the last filling of a variable in a string

How to replace the last occurrence of a variable (foo) in a string with "foo"?

I tried:

var re = new RegExp(".*" + (foo))); var newText = currentText.replace(re, someThingElse); 
-one
javascript regex
Mar 21 '15 at 21:43
source share
2 answers

Negative-lookahead will work, but it will

 newText = newText.replace(new RegExp("(.*)" + foo), "$1somethingElse"); 
+2
Mar 21 '15 at 21:56
source share

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" 
+1
Mar 21 '15 at 21:49
source share



All Articles