简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM