jQuery: tweetify text

jQuery: tweetify text

How to format an HTML string just like a tweet with jQuery.

With the new verb tweetify, coined by Twitter users and web developers, we simply mean formatting an HTML string just like a tweet, namely with all plain links, usernames and hashtags turned into their corresponding HTML links. In this article we'll see how to accomplish this task with jQuery.

We can create the following plugin that makes use of three different JavaScript regular expressions:

(function($) {
    $.fn.tweetify = function() {
        var that = this;
        var html = that.html();
        that.each(function() {
            $(that).html(
            html.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi, '<a href="$1">$1</a>').replace(/(^|\s)@(\w+)/g, '$1<a href="http://twitter.com/@$2">@$2</a>').
            replace(/(^|\s)#(\w+)/g, '$1<a href="http://twitter.com/search/#$2">#$2</a>'));
        });
        return this;
    }
})(jQuery);

All the regular expressions used above implements their patterns as capturing groups. This means that we can reference the matched group with $1, $2 etc. in the replace() method.

Example:

$('#test').tweetify();​

You can see the demo below.

Demo

Live demo