简体   繁体   English

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

[英]Javascript split by spaces, but not within html-tags

My first goal is to split a string by spaces, but not the ones within html-tags. 我的第一个目标是用空格分隔字符串,而不是用html-tags分隔。

I've tried to rewrite the following, unsuccessfully: Javascript split by spaces but not those in quotes 我试图重写以下内容, 但未成功: 用空格分隔的Javascript,但没有用引号引起来的Javascript

What would the regex look like in: arr = fullHtmlString.split( ? ); 正则表达式的外观如下:arr = fullHtmlString.split( ); ?


My main goal is to shift an IMG-tag by one space at a time. 我的主要目标是一次将IMG标签移动一个空格。 After that I'll iterate over the array, search for the img-tag, remove it, and add it the next item, and finally join the array. 之后,我将遍历数组,搜索img-tag,将其删除,然后将其添加到下一项,最后加入数组。

The code I use at the moment is quite comprehensive and use jQuery extensively to achive the goal. 我目前使用的代码非常全面,并广泛使用jQuery实现目标。

Input: 输入:

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

Deisred output first time: 第一次期望的输出:

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

...second time: ...第二次:

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

...third time: ...第三次:

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

You should not try to do this with a regular expression, why explained here . 您不应该尝试使用正则表达式来执行此操作, 为什么要在此处进行说明

You can use DOM properties and methods though 您可以使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM