Aug 12

Converting a URL into a Link in JavaScript - Linkify Function

A useful function to process text converting all URLs into links

I previously implemented something similar in C#, and now I have it in JavaScript. Pass in a bunch of text and get it back with the URLs converted into clickable links (<a />'s).

function linkify(text){
    if (text) {
        text = text.replace(
            /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
            function(url){
                var full_url = url;
                if (!full_url.match('^https?:\/\/')) {
                    full_url = 'http://' + full_url;
                }
                return '<a href="' + full_url + '">' + url + '</a>';
            }
        );
    }
    return text;
}

Tags:

Powered by my hackings on Django-Mingus a Django project, PostgreSQL, memcached, nginx, Apache + mod_wsgi, Ubuntu, Rackspace Cloud,...

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

html5 | top