Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #296 Replace last occurrence of substring

Assign to x2 the value of string x with the last occurrence of y replaced by z.
If y is not contained in x, then x2 has the same value as x.

$x = 'A BB CCC this DDD EEEE this FFF';
$y = 'this';
$z = 'that';

$x2 = $x;
$pos = rindex $x, $y;
substr($x2, $pos, length($y)) = $z
    unless $pos == -1;

print $x2;

perl substr can be used as an lvalue, which is ideal here. We use rindex to find the last occurence of substring $y in $x and use that position in a substr of a copy of $x called $x2. Assigning $z to the substring replaces it -- but we skip that if rindex didn't find the substring.
var position = x.lastIndexOf(y).clamp(0, x.length);
var x2 = x.replaceFirst(y, z, position);

New implementation...
< >
programming-idioms.org