我需要更换流动的:
<a href="#">something</a>
withthis:
(start-a)something(end-a)
我没有掌握正则表达式,所以正则表达式我只是完全改变所有标签。
string.replace(/(<([^>]+)>)/ig,"(start-a)");
我应该更改我的正则表达式,只更换第一个标签,另一个更改是替换结束标签?
感谢。
答案 0 :(得分:1)
// 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);
});
&#13;
<div>
<a href="#">something</a>
<a href="#">something</a>
<a href="#">something</a>
<a href="#">something</a>
<a href="#">something</a>
</div>
&#13;