9

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?

3 Answers 3

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>");
Sign up to request clarification or add additional context in comments.

1 Comment

str.replace(/([\s\S]*)<br>/, "$1"); for multiline.
3

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.

2 Comments

Wouldnt you want it to be: str.replace(/^(.*)((<br>)*?)$/, '$1$2') so as to include the <br> in the last match?
The whole idea is to remove the last <br>
-1
String.prototype.replaceLast = function(what, replacement) { 
    return this.replace(new RegExp('^(.*)' + what + '(.*?)$'), '$1' + replacement + '$2');
}

str = str.replaceLast(what, replacement);

1 Comment

An answer solely consisting of code with no or little explanation makes it difficult to understand for future visitors which approach the asker should take and why your answer is viable. Please add explanations to your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.