replace multiple <br> tags with javascript

This question already has an answer here:

  • How to replace all occurrences of a string in JavaScript? 41 answers

  • You have specified that it's in document.body , so in the DOM. Then you can (and you should) use DOM methods:

    var siblingBrs = [].slice.call( document.querySelectorAll('br + br') );
    siblingBrs.forEach( function( br ){
        br.parentNode.removeChild( br );
    });
    

    http://jsfiddle.net/jL8jkkt0/

    Notice it's agnostic to the string representation of a <br /> element in the source code.

    BTW if it's only for display purposes (to avoid visual gap) you can just use CSS:

    br + br { display:none; }
    

    http://jsfiddle.net/jL8jkkt0/1/


    Try the following:

    var stripped = original.replace(/(<brs*/?>){3,}/gi, '<br>');
    

    Substituting different values here...

    {3,}
    

    ...will allow you to control at what count the removal occurs.

    Hope this helps!


    首先获取HTML作为字符串,然后使用正则表达式替换它:

    var s = document.body.innerHTML;
    document.body.innerHTML = s.replace(/(<br[s]*/?>[s]*)+/g, '<br/>');
    First Line<br><br /><br/><br><br /><br/>Second Line
    链接地址: http://www.djcxy.com/p/94038.html

    上一篇: 匹配可能有特殊字符的单词

    下一篇: 用javascript替换多个<br>标记