最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - how to replace last occurrence of a word in javascript? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Apr 30, 2017 at 14:44 Cœur 38.7k26 gold badges202 silver badges277 bronze badges asked May 9, 2009 at 9:59 omgomg 140k145 gold badges291 silver badges351 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

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>");

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.

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

str = str.replaceLast(what, replacement);
发布评论

评论列表(0)

  1. 暂无评论