Platinum Partner

Autolinking Text With Javascript (linkify)

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 '' + prototype.string.autolinkLabel(nice, options.limit) + '';
    });
    
    return string;
};


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

    if (!limit){ return text; }

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

    return text;
};

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}