Javascript - How to remove link within links
Let's say a string contains <a href="http://google.com">http://google.com</a>
. When I linkify the whole string (that has both unlinked URLs and linked URLs, like the one shown above), it will become <a href="<a "" href开发者_开发知识库="http://google.com"">http://google.com"</a>>http://google.com</a>
.
Is there a way to revert the incorrect links (which are the ones already linked before linkifying) back to <a href="http://google.com">http://google.com</a>
?
I found in WordPress, that it uses $ret = preg_replace("#(]+?>|>))]+?>([^>]+?)#i", "$1$3", $ret);
(in wp-includes/formatting.php) to accomplish this. Can someone help me to do this in JavaScript?
Have a look at this http://jsfiddle.net/mplungjan/V5Qca/
<script>
function linkify(id,URL) {
var container = document.getElementById(id);
var links = container.getElementsByTagName("a");
if (links.length ==0) {
container.innerHTML=container.innerHTML.link(URL);
return;
}
var nodes = container.childNodes;
for (var i=nodes.length-1;i>=0;--i) {
if (nodes[i].nodeType ==3 && nodes[i].parentNode.nodeName!="A") {
var link = document.createElement("a");
link.href=URL;
link.innerHTML=nodes[i].nodeValue;
container.replaceChild(link, nodes[i]);
}
}
}
window.onload=function() {
linkify("div1","http://www.google.com/");
}
</script>
<div id="div1">
this is a <a href="test">test</a> of replacing text with links with <a href="#">linkified</a> content
</div>
精彩评论