Javascript 按空格分隔,但不在 html 标签内

Javascript split by spaces, but not within html-tags

我的第一个目标是将字符串拆分 spaces,而不是 html-tags 中的字符串。

我尝试重写以下内容,但未成功:Javascript split by spaces but not those in quotes

正则表达式在以下情况下会是什么样子: arr = fullHtmlString.split(?); ?


我的主要目标是一次将 IMG 标签移动一个 space。 之后,我将遍历数组,搜索 img-tag,将其删除,并将其添加到下一项,最后加入数组。

我目前使用的代码非常全面,广泛使用 jQuery 来实现目标。

输入:

<div>
    <p><img class=something>Some text.</p>
    <p>Some more text.</p>
</div>

Deisred 第一次输出:

<div>
    <p>Some<img class=something> text.</p>
    <p>Some more text.</p>
</div>

...第二次:

<div>
    <p>Some text.<img class=something></p>
    <p>Some more text.</p>
</div>

...第三次:

<div>
    <p>Some text.</p>
    <p><img class=something>Some more text.</p>
</div>

您不应尝试使用正则表达式来执行此操作,why explained here

不过您可以使用 DOM 属性和方法

function run(){
  var img  = document.querySelector(".something"),
   sibling = img,
   parent  = img.parentNode,
   next    = parent.nextElementSibling;

  //Search for the next textNode
  while((sibling = sibling.nextSibling) && sibling.nodeType !=3);

  if(sibling) {
    //split the text only once, 
    //so "some more text" becomes ["some","more text"]
    var textParts = sibling.textContent.split(/ (.*)?/,2);

    //put the first split item before the sibling
    parent.insertBefore(document.createTextNode(textParts[0]+" "),sibling);

    //replace the sibling with the img element
    parent.replaceChild(img,sibling);

    //finally if there was more text insert it after the img
    textParts[1] && parent.insertBefore(document.createTextNode(textParts[1]),img.nextSibling);    
  } else if(!sibling && next) {
    //no sibling in the current parent, 
    //so prepend it to the next available element in parent
    next.insertBefore(img,next.firstChild);
  } else {
    clearInterval(timer);
  }
}

var timer = setInterval(run,2000);
<div>
    <p><img class="something" src="http://placehold.it/10x10">Some text.</p>
    <p>Some <span>skip me</span> more text.</p>
</div>