Naveen K
Naveen K

Reputation: 889

replace multiple <br> in javascript replace with single <br>?

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

Upvotes: 3

Views: 4179

Answers (2)

Gurpreet Singh
Gurpreet Singh

Reputation: 21233

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.

Upvotes: 6

Ja͢ck
Ja͢ck

Reputation: 173662

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>')

Upvotes: 5

Related Questions