2017-11-30 16 views
-4

私は交換する必要が流れる:変更開始タグと終了タグは、別途

<a href="#">something</a> 

withthis:

(start-a)something(end-a) 

私はうまく正規表現をマスターしていないので、正規表現は、私はそのわずか変更する必要がありますすべてのタグを完全に

string.replace(/(<([^>]+)>)/ig,"(start-a)"); 

最初のタグを置き換えるだけで正規表現を変更しても、終了タグを置き換えるために変更する必要はありますか?

ありがとうございました。

+1

あなたが代わりに正規表現のDOMメソッドを使用する必要があります。 [義務的な標準リンク](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags#1732454) –

+0

@DanielBeck私に例を教えてください。 – domoindal

+0

https://stackoverflow.com/questions/843680/how-to-replace-dom-element-in-place-using-javascript –

答えて

1
  1. 置き換えるタグをすべて見つけます。
  2. 各タグに基づいて新しいテキストノードを作成します。
  3. 新しいノードを挿入します。
  4. 古いタグを削除します。

// Find all tags to be replaced and put in an Array and loop through them 
 
var tags = Array.prototype.slice.call(document.querySelectorAll("a")).forEach(function(tag){ 
 
    // Find the parent element of the node 
 
    var parent = tag.parentNode; 
 
    
 
    // Create a new text node with the contents of the current element 
 
    var replaceString = document.createTextNode("(start-a)" + tag.textContent + "(end-a)"); 
 
    
 
    // Insert the new text node where the current tag is 
 
    parent.insertBefore(replaceString, tag); 
 
    
 
    // Delete the old tag 
 
    parent.removeChild(tag); 
 
});
<div> 
 
    <a href="#">something</a> 
 
    <a href="#">something</a> 
 
    <a href="#">something</a> 
 
    <a href="#">something</a> 
 
    <a href="#">something</a> 
 
</div>

+0

信じられないほど!!!!それはちょうど私が探していたもの...ありがとう!!!!! – domoindal

+0

FYIは、slice.callなしで 'document.querySelectorAll(" a ")。forEach'を使用できます。 – charlietfl

+1

@charlietfl実際には、[すべてのブラウザで](https://developer.mozilla.org/en-US)できません。/docs/Web/API/NodeList/forEach)。 (IE any、Android)。 –

関連する問題