Is there any way to use replace method for last occuring characters in a string?

Viewed 161
var str = "lala";
var newStr = str.replace('l', 'm');

The value of newStr becomes 'mala', as the replace method finds the first occurrence of character in the string and replaces the character and then stops.

But I want the output "lama". How can I achieve it?

8 Answers

You can use regex for this:

var str = "lala";
var newStr = str.replace(/l([^l]*)$/, 'm$1'); // lama
console.log(newStr);

This pattern matches an l followed by any number of characters that are not l until the end of the string. This will only match one time since the string ends only once (i.e in "lalblc" it matches "lc"). Then it replaces "lc" with "m" followed by the group of letters after the l (which is "c"). In the end, you are left with the original string but with the last l replaced with m.

[^l] means "any letter that is not l"

* means "any number of times (0 or more)"

The parenthesis create a capturing group which can be referenced using $1 in the replacement.


If you will be doing this frequently, it would be useful to move this to a function. You can make a function, replaceLast that can be called on strings by doing:

String.prototype.replaceLast = function (search, replace) {
    return this.replace(new RegExp(search+"([^"+search+"]*)$"), replace+"$1");
}

str = "lala";
newStr = str.replaceLast("l", "m");
console.log(newStr);

You can match everything up to an "l" followed by anything that's not an "l":

    var str = "lala";
    var newStr = str.replace(/(.*)l([^l]*)$/, "$1m$2");
    console.log(newStr);

The first group, (.*), will consume as much of the string as it can. The second group, ([^l]*)$, will match the rest of the source string after the last "l".

Here i've created a custom function also i've avoided using any regex since it's quite difficult for any beginner to understand.

var str = "lala";

const customReplace = (replaceChar, replaceWith, str) => {
  const lastIndex = str.lastIndexOf(replaceChar);
  const leftPortion = str.slice(lastIndex);
  const rightPortion = str.slice(lastIndex+1);

  return `${leftPortion}${replaceWith}${rightPortion}`;
}

console.log(customReplace('l', 'm', str))  

You can use reverse, replace and reverse again.

You could take a search for l which is not followed by optional non l characters and an l.

var str = "lala",
    newStr = str.replace(/l(?![^l]*l)/, 'm');

console.log(newStr);

or you can use Look ahead in RegEx to find the last character :

var str = "lala";
var newStr = str.replace(/l(?!.*l)/, 'm');
console.log(newStr);

for more information you can read this link

Here is a straightforward way to replace, a bit silly but it works as well

var str = "lalalc";
var newStr = [...str];
newStr[str.lastIndexOf('l')] ='m';
newStr.join('');

You can use this Regex to replace second occurance of letter:

var str = "lala";
var newStr = str.replace(/(?<=l.*?)l/,"m"); 
console.log(newStr);

Related