0

given this markup:

<div class="myclass">
    Lorem ipsum dolor sit amet, http://example.com consectetuer adipiscing elit.
</div>

I need a jQuery function, which (after the dom ready event) finds all .myclass divs and transforms the strings which starts with http(s):// into links, so that the above example markup results in this:

<div class="myclass">
    Lorem ipsum dolor sit amet, <a href="http://example.com">http://example.com</a> consectetuer adipiscing elit.
</div>

Can you help?

Thanks sub

sub
  • 157
  • 1
  • 5

2 Answers2

2
(function($) {
    $(function() {
        $('.myclass').each(function() {
            var el = $(this);

            if (el.html().indexOf('http') > -1) {
                var html = el.html();

                html = html.replace(/(https?:[\S]+)/gi, '<a href="$1">$1</a>');

                el.html(html);
            }
        });
    });
})(jQuery);

fiddle

Alex
  • 9,911
  • 5
  • 33
  • 52
1

I think that regular expression here have what you need.

function:

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}
Community
  • 1
  • 1
Alessandro Gomes
  • 521
  • 1
  • 5
  • 14