”?
提问者:小点点

如何将“<br>”替换为“</div><div>”?


我得到了一个导入的文本块,但格式并不总是那么完美。之后我会尝试用jquery解决这个问题。所以我开始用

替换
:

null

$('.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>

null

但替换不起作用。最终的html应该如下所示:

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

共1个答案

匿名用户

您需要用替换的对象更新DOM!

换一下就行了

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

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

null

$('.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>