Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...