jQuery: turning strings into links

Some popular social networks don't accept HTML markup in their formats, so they render and store URLs as text. Sometimes this can cause some problems especially when we want to display such URLs as normal HTML links. With jQuery and a simple regular expression (you can find many more regular expressions that match URLs on the web), we can turn these strings into links by using the JavaScript function replace(). Here's how:

(function($) {


    $.fn.toLink = function() {
    
    
        var text = this.text();
        var urlRegExp = /((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/gm;
        
        if(!urlRegExp.test(text)) {
        
            throw new Error('This is not a valid URL.');
            
            return;
        
        
        }
        
        var newText = text.replace(urlRegExp, '<a href="$1">$1</a>');
        
        this.html(newText);
        
        return this;
    
    
    };



})(jQuery);

The replace() function is used here with the global and multiline options. The notation $1 signifies that the content of the href attribute and of the link itself will be generated using the first match of the regular expression. Here's a simple demo:

$(document).ready(function() {


    $('#run').click(function() {
    
    
       $('ul li').each(function() {
       
       
           $(this).toLink();
       
       
       });
    
        return false;
    
    });



});

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.