0

I am using this regex to replace links in HTML:

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

As you can see, it will convert text URLs (that ends with .png, .jpg or .gif) to img-tags. However, I have some issues with this regex, see below:

  • It replaces links inside html tags, and breaks the markup
  • It does not work with https://, if the original url is https:// it should be that after the replacement too and not http://.

Can somebody come up with improvements to this?

Robin
  • 187
  • 1
  • 10

2 Answers2

1

To fix your regex to also match https, add s? after http:

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

To fix your problem with replacing links in html tags, you can do like this to select all textNodes:

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

Here's an example:

$("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
Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28
  • Very nicely done! So, the markup issue cannot be fixed in the regex? This would be a better way of doing it to save system resources? – Robin Dec 26 '15 at 14:22
  • @Robin Yes, http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Johan Karlsson Dec 26 '15 at 14:31
0

change your regex to

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

where s? means s is optional

this will supports https url

btw I'm not really understand your question 1

user3896501
  • 2,987
  • 1
  • 22
  • 25