用HTML中的链接替换url

Replacing urls with links in HTML

本文关键字:替换 url 链接 HTML      更新时间:2023-09-26

我有一些HTML进来:

<img src="http://www.example.com/image.jpg" />
<a href="http://www.example.com">Example.com</a>
http://www.example.com

在另一个线程我发现这个正则表达式:

var exp = /('b(https?|ftp|file):'/'/[-A-Z0-9+&@#'/%?=~_|!:,.;]*[-A-Z0-9+&@#'/%=~_|])/i;

问题是它也改变了img和a标签:

<img src="<a href="http://www.example.com/image.jpg">http://www.example.com/image.jpg</a>" />
<a href="<a href="http://www.example.com">http://www.example.com</a>">Example.com</a>
<a href="http://www.example.com">http://www.example.com</a>

有什么想法来处理这个快速而不必解析HTML?

使用regex进行html处理会引起类似的错误,而不是尝试使用regex进行dom处理,如

var string = '<img src="http://www.example.com/image.jpg" /> '
<a href="http://www.example.com">Example.com</a>'
http://www.example.com';
var $tmp = $('<div />', {
  html: string
});
var exp = /('b(https?|ftp|file):'/'/[-A-Z0-9+&@#'/%?=~_|!:,.;]*[-A-Z0-9+&@#'/%=~_|])/i;
$tmp.contents().contents().addBack().each(function() {
  if (this.nodeType == Node.TEXT_NODE && exp.test(this.nodeValue)) {
    $(this).replaceWith(function() {
      return $('<div />', {
        html: this.nodeValue.replace(exp, '<a href="$1">$1</a>')
      }).contents()
    })
  }
});
var processed = $tmp.html();
snippet.log(processed)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

最后遍历HTML。这不是最快的解决方案,但有效:

$(id).find('*').each(function(k,v)
{
    if (v.nodeName == 'A')
    {
    // do stuff 
    }
}