【问题标题】:Javascript - How to remove link within linksJavascript - 如何删除链接中的链接
【发布时间】:2011-05-16 06:52:27
【问题描述】:

假设一个字符串包含<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>

有没有办法将不正确的链接(在链接之前已经链接的链接)还原回<a href="http://google.com">http://google.com</a>

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

【问题讨论】:

  • 链接前为什么不检查字符串??

标签: javascript regex hyperlink linkify


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-06-17
    • 2011-12-09
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    相关资源
    最近更新 更多