简体   繁体   中英

How can I replace "<br>" with "</div><div>"?

I get an imported text block, but the formatting is not always so perfect. I try to fix this with jquery afterwards. So I started to replace <br> with <div></div> :

 $('.details').html().replace(/<br>\\*/g,"</div><div>"); if ($('.details div').is(':empty')) { $(this).remove(); }
 .details div { font-size: 11px; color: #777; letter-spacing: 1px; text-transform: uppercase; padding: 4px 0; margin: 0; border-top: 1px solid rgba(0,0,0, .05); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="details"> monkey<br> elephant<br> rabbit<br> sun<br> moon<br><div> bird <br></div><div><br></div><div>gras</div><div></div><span> house<br> way<br> silience<br></span><div> love <br></div><div><br></div><div>somewhere <br></div><div><br></div><div><span>land</span></div><div></div><div><span> kanguroo</span> <br></div><div><br></div><div>tv</div> </div>

But the replace is not working. The final html should look like this:

<div class="details">
    <div>monkey</div>   
    <div>elephant</div> 
    <div>rabbit</div>   
    <div>sun</div>  
    <div>moon</div> 
    <div>bird</div> 
    <div>gras</div>
    <div>house</div>    
    <div>way</div>  
    <div>silience</div> 
    <div>love</div> 
    <div>somewhere</div>    
    <div>land</div>
    <div>kanguroo</div> 
    <div>tv</div>                                                          
 </div>

You need to update the DOM with your replacement!

Just change

$('.details').html().replace(/<br>\\*/g,"</div><div>");

to

$('.details').html($('.details').html().replace(/<br>\\*/g,"</div><div>"));

 $('.details').html($('.details').html().replace(/<br>\\*/g,"</div><div>")); $('.details div:empty').remove();
 .details div { font-size: 11px; color: #777; letter-spacing: 1px; text-transform: uppercase; padding: 4px 0; margin: 0; border-top: 1px solid rgba(0,0,0, .05); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="details"> monkey<br> elephant<br> rabbit<br> sun<br> moon<br><div> bird <br></div><div><br></div><div>gras</div><div></div><span> house<br> way<br> silience<br></span><div> love <br></div><div><br></div><div>somewhere <br></div><div><br></div><div><span>land</span></div><div></div><div><span> kanguroo</span> <br></div><div><br></div><div>tv</div> </div>

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