0

I have two Regex expressions, which each find either URLs, like http://www.google.com, or image links like https://www.google.com/images/srpr/logo11w.png.

This one finds URLs, like http://www.google.com

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

And this one finds URLs with image extensions like https://www.google.com/images/srpr/logo11w.png

/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])+\.(?:jpe?g|gif|png)/ig;

I have a function that looks though text, and replaces URLs with <a href="...">...</a> and <img src="..."> like this:

function replaceURLWithHTMLLinks(text) {
        var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
        var exp2 = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])+\.(?:jpe?g|gif|png)/ig;
        var links = text.replace(exp,"<a href='$1' target='_blank'>$1</a>");
        var images = links.replace(exp2, "<img src='$1' alt='$1'>");
        return images;
    }

The problem is, if I have text like which contains image urls, it finds the URL on the first run and replaces it with an link, and then replaces some of the link in the second part, breaking it.

It's best explained in this fiddle: http://jsfiddle.net/BenedictLewis/m4H9B/2/

1 Answer 1

0

Use look-ahead to look for surrounding quotes

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

Example: http://jsfiddle.net/S9TbH/1/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.