Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 796
HTMLBoy Avatar asked Mar 03 '23 17:03

HTMLBoy


2 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);
like image 104
DenverCoder1 Avatar answered Mar 05 '23 09:03

DenverCoder1


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".

like image 27
Pointy Avatar answered Mar 05 '23 07:03

Pointy