Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

regex - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...