0

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);
SuperUberDuper
  • 9,242
  • 9
  • 39
  • 72

2 Answers2

2

The negative-lookahead would work, but so will

newText = newText.replace(new RegExp("(.*)" + foo), "$1somethingElse");
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Using a greedy `*` will be better than a negative lookahead if you don't need to use part of the match in the replacement. Also, `.*` will not match over new lines – Paul S. Mar 21 '15 at 21:59
  • Will this also add back the text after foo in my original string? – SuperUberDuper Mar 21 '15 at 22:00
  • 1
    @SuperUberDuper in this instance it is the text _before_ that is being replaced back in – Paul S. Mar 21 '15 at 22:05
1

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"
Paul S.
  • 64,864
  • 9
  • 122
  • 138