[英]Javascript split by spaces, but not within html-tags
我的第一個目標是用空格分隔字符串,而不是用html-tags分隔。
我試圖重寫以下內容, 但未成功: 用空格分隔的Javascript,但沒有用引號引起來的Javascript
正則表達式的外觀如下:arr = fullHtmlString.split( ? ); ?
我的主要目標是一次將IMG標簽移動一個空格。 之后,我將遍歷數組,搜索img-tag,將其刪除,然后將其添加到下一項,最后加入數組。
我目前使用的代碼非常全面,並廣泛使用jQuery實現目標。
輸入:
<div>
<p><img class=something>Some text.</p>
<p>Some more text.</p>
</div>
第一次期望的輸出:
<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>
您不應該嘗試使用正則表達式來執行此操作, 為什么要在此處進行說明 。
您可以使用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.