3

I want to replace the multiple <br> tags with single <br> in a text.

my text like,

<p>fhgfhgfhgfh</p>
<br><br>
<p>ghgfhfgh</p>
<br><br>
<p>fghfghfgh</p>
<br><br>
<p>fghfghfgh</p>
<br><br>
<p>fghfgh</p>
<br><br>

How i replace the multiple <br> with single <br>?.

0

2 Answers 2

6

Try this

var str="<p>fhgfhgfhgfh</p><br><br><p>ghgfhfgh</p><br><br><p>";

var n=str.replace(/<br><br>/g,"<br>");

console.log(n);

Working DEMO

Edit: Above works for 2 br tags, code below should take care of any number of br tags.

var n = str.replace(/(<br>)+/g, '<br>');

Working DEMO

where /.../ denotes a regular expression, (<br>) denotes <br> tag, and + denotes one or more occurrence of the previous expression and finally g is for global replacement.

Sign up to request clarification or add additional context in comments.

Comments

5

This should do the trick:

str.replace(/(?:<br>){2,}/g, '<br>')

Or, if they can be on different lines:

str.replace(/(?:<br>\s*){2,}/g, '<br>')

Comments

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.