omg
omg

Reputation: 139872

how to replace last occurrence of a word in javascript?

for example:

var str="<br>hi<br>hi";

to replace the last(second) <br>,

to change into "<br>hihi"

I tried:

str.replace(/<br>(.*?)$/,\1);

but it's wrong. What's the right version?

Upvotes: 9

Views: 9799

Answers (3)

zaxvox
zaxvox

Reputation: 9

String.prototype.replaceLast = function(what, replacement) { 
    return this.replace(new RegExp('^(.*)' + what + '(.*?)$'), '$1' + replacement + '$2');
}

str = str.replaceLast(what, replacement);

Upvotes: -1

Gumbo
Gumbo

Reputation: 655239

You can use the fact that quantifiers are greedy:

str.replace(/(.*)<br>/, "$1");

But the disadvantage is that it will cause backtracking.

Another solution would be to split up the string, put the last two elements together and then join the parts:

var parts = str.split("<br>");
if (parts.length > 1) {
    parts[parts.length - 2] += parts.pop();
}
str = parts.join("<br>");

Upvotes: 13

Greg
Greg

Reputation: 321638

I think you want this:

str.replace(/^(.*)<br>(.*?)$/, '$1$2')

This greedily matches everything from the start to a <br>, then a <br>, then ungreedily matches everything to the end.

Upvotes: 3

Related Questions