DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Autolinking Text With Javascript (linkify)

03.05.2009
| 6582 views |
  • submit to reddit
        Here is how you can autolink your text using javascript.

I'm using namespaces to declare functions. Code needs 2 simple functions to work correctly: string.autolink() - the main function - and string.autolinkLabel() (just used to nice-i-fy url).

//Usage example (using jQuery):
$(function(){
    prototype.string.autolink($('#my-div-with-plain-text').text());
    
    //note: u can still pass two more arguments (as an object): @limit and @tagFill
});

Enjoy!


var prototype = {};
prototype.string = {};

prototype.string.autolink = function (string, options){
    if(!options) options = {};
    if(!options.limit) options.limit = 10;
    if(!options.tagFill) options.tagFill = '';
    
    var regex = /((http\:\/\/|https\:\/\/|ftp\:\/\/)|(www\.))+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi;
    
    string = string.replace(regex, function(value){
        value = value.toLowerCase();
        var m = value.match(/^([a-z]+:\/\/)/);
        var nice;
        var url;
        
        if(m)
        {
            nice = value.replace(m[1],'');
            url = value;
        }
        else
        {
            nice = value;
            url = 'http://' + nice;
        }
        
        return '<a href="' + url + '"' + (options.tagFill != '' ? (' ' + options.tagFill) : '')+ '>' + prototype.string.autolinkLabel(nice, options.limit) + '</a>';
    });
    
    return string;
};


prototype.string.autolinkLabel = function (text, limit){

    if (!limit){ return text; }

    if (text.length > limit){
        return text.substr(0, limit - 3) + '...';
    }

    return text;
};