2011-05-16 91 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>