How to wrap part of a text in a node with JavaScript

后端 未结 5 1331
-上瘾入骨i
-上瘾入骨i 2020-11-28 23:36

I have a challenging problem to solve. I\'m working on a script which takes a regex as an input. This script then finds all matches for this regex in a document and wraps ea

5条回答
  •  粉色の甜心
    2020-11-29 00:33

    function parseText( element ){
      var stack = [ element ];
      var group = false;
      var re = /(?!\s|$).*?(\.|$)/;
      while ( stack.length > 0 ){
        var node = stack.shift();
        if ( node.nodeType === Node.TEXT_NODE )
        {
          if ( node.textContent.trim() != "" )
          {
            var match;
            while( node && (match = re.exec( node.textContent )) )
            {
              var start  = group ? 0 : match.index;
              var length = match[0].length + match.index - start;
              if ( start > 0 )
              {
                node = node.splitText( start );
              }
              var wrapper = document.createElement( 'span' );
              var next    = null;
              if ( match[1].length > 0 ){
                if ( node.textContent.length > length )
                  next = node.splitText( length );
                group = false;
                wrapper.className = "sentence sentence-end";
              }
              else
              {
                wrapper.className = "sentence";
                group = true;
              }
              var parent  = node.parentNode;
              var sibling = node.nextSibling;
              wrapper.appendChild( node );
              if ( sibling )
                parent.insertBefore( wrapper, sibling );
              else
                parent.appendChild( wrapper );
              node = next;
            }
          }
        }
        else if ( node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.DOCUMENT_NODE )
        {
          stack.unshift.apply( stack, node.childNodes );
        }
      }
    }
    
    parseText( document.body );
    .sentence {
      text-decoration: underline wavy red;
    }
    
    .sentence-end {
      border-right: 1px solid red;
    }

    This is a sentence. This is another sentence.

    This sentence has emphasis inside it.

    This sentence spans two elements.

提交回复
热议问题