Replace multiple
's with only one

前端 未结 9 2102
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 12:55

How do I use JavaScript to detect




to become one


?

I trie

相关标签:
9条回答
  • 2021-02-01 13:28

    Wouldn't something like this be the right approach:

    $("br~br").remove()
    

    EDIT: No, it's wrong, because its definition of "contiguous" is too loose, as per BoltClock.

    0 讨论(0)
  • 2021-02-01 13:29

    Simpler:

    var newText = oldText.replace(/(<br\s*\/?>){3,}/gi, '<br>');

    This will allow optional tag terminator (/>) and also spaces before tag end (e.g. <br /> or <br >).

    0 讨论(0)
  • 2021-02-01 13:32

    A lot of the other answers to this question will only replace up to certain amount of elements, or use complex loops. I came up with a simple regex that can be used to replace any number of <br> tags with a single tag. This works with multiple instances of multiple tags in a string.

    /(<br>*)+/g
    

    To implement this in JavaScript, you can use the String.replace method:

    myString.replace(/(<br>*)+/g, "<br/>");
    

    To replace multiple <br/> tags, add a / to the regex:

    /(<br\/>*)+/g
    
    0 讨论(0)
提交回复
热议问题