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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.