2011-05-16 61 views
0

假设一个字符串包含<a href="http://google.com">http://google.com</a>。当我链接整个字符串(既有未链接的URL又有链接的URL,如上面所示)时,它将变为<a href="<a "" href="http://google.com"">http://google.com"</a>>http://google.com</a>Javascript - 如何删除链接内的链接

有没有办法将不正确的链接(链接前已链接的链接)恢复为<a href="http://google.com">http://google.com</a>

我发现在WordPress中,它使用$ret = preg_replace("#(]+?>|>))]+?>([^>]+?)#i", "$1$3", $ret);(在wp-includes/formatting.php中)来实现此目的。有人可以帮助我在JavaScript中做到这一点?

+0

你为什么不linkifying前检查字符串? – 2011-05-16 06:56:37

回答

0

看一看这个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>