Twitter status text links made clickable

23rd February 2010 by Jason C. Filed under: Code-bits

A new design agency being formed by an existing client needed a site. They had a good design ready, I just had to build the thing. It’s built in Wordpress, but I also pull in their Twitter stream on the client side.

Twitter’s api is easy enough to use. I opted for the JSON-p format, but something I didn’t realise at the time was that the status updates are purely the plain text. So any URLs, usernames or hashtags are just plain text: no wrapping in <a></a> tags. It’s an easy problem to solve, though, and here it is for anyone else who needs it.

function twitify( text )
{
    // replace urls with linked ones
    var t2 = text.replace(/(http|https)(:\/\/)([^ ]+)/ig, '<a href="$1$2$3">$1$2$3</a>' );

    // replace @username with clickable twitter link
    t2 = t2.replace(/@([^ ]+)/gi,'<a href="http://twitter.com/$1">@$1</a>');

    // replace hashtags with Twitter searches
    t2 = t2.replace(/#([^ ]+)/gi,'<a href="http://search.twitter.com/search?q=%23$1">#$1</a>');

    return t2;
}

So, feed the tweet into that function, and back out it comes with links, @users and #hastags made clickable.

Did I mention I ♥ regular expressions?

Tags: , ,

Leave a Reply