正则表达式 - 用图像标记替换URL

时间:2015-12-26 13:07:57

标签: javascript regex

我正在使用此正则表达式替换HTML中的链接:

$(...).replace(/(http:\/\/\S+(\.png|\.jpg|\.gif))/g, '<a href="$1"><img src="$1" /></a>');

如您所见,它会将文本网址(以.png,.jpg或.gif结尾)转换为img-tags。但是,我对此正则表达式有一些问题,请参阅下文:

  • 它取代了html标签内的链接,并打破了标记
  • 它不适用于https://,如果原始网址是https://也应该是替换后的,而不是http://。

有人可以提出改进吗?

2 个答案:

答案 0 :(得分:1)

要修复您的正则表达式以匹配https,请在s?之后添加http

/(https?:\/\/\S+(\.png|\.jpg|\.gif))/g

要修复替换html标记中的链接的问题,您可以这样做以选择所有textNodes:

$("body").find("*").addBack().contents().filter(function() {
  return this.nodeType == 3;
})

以下是一个例子:

$("body").find("*").addBack().contents().filter(function() {
  return this.nodeType == 3;
}).each(function(index, element) {
  $(element).replaceWith(element.textContent.replace(/(https?:\/\/\S+(\.png|\.jpg|\.gif))/g, '<a href="$1"><img src="$1" /></a>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Some text<br>
<div>
  Should be picture: https://pic.jpg
</div>

Another picture here:
http://www.example.com/pic.png

<p>
  <div>
    URL in a.href doesn't change:
    <a href="http://www.example.org">
        But here it does: https://www.example.net/pic.gif
    </a>
    <br>
    URL in img.src doesn't change:
    <img src="https://www.example.net/img/abc.jpg">
  </div>
</p>
MOAR TEXT

答案 1 :(得分:0)

将正则表达式更改为

/(https?:\/\/\S+(\.png|\.jpg|\.gif))/g

哪里有s?意味着s是可选的

这将支持https网址

btw我真的不明白你的问题1

相关问题