Replace multiple
's with only one

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

How do I use JavaScript to detect




to become one


?

I trie

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 13:08

    This solution is jQuery + DOM only, does not manipulate HTML as string, works with text nodes, ignores whitespace only text nodes:

    $('br').each(function () {
      const {nodeName} = this;
    
      let node = this;
    
      while (node = node.previousSibling) {
        if (node.nodeType !== Node.TEXT_NODE || node.nodeValue.trim() !== '') {
          break;
        };
      }
    
      if (node && node !== this && node.nodeName === nodeName) {
        $(node).remove();
      }
    });
    

    See: https://jsfiddle.net/kov35jct/

提交回复
热议问题