Friday, February 25, 2011

Tweetify Plain Text

When we use twitter API to retrieve the tweets, it gives us the plain text that has to be converted into proper html so that they are rendered to web user in a more usable fashion. For this we need to do three tasks :
1. Replace plain text urls to anchor tags pointing to those urls.
2. Replace @username with proper anchor tags pointing to their twitter accounts.
3. Replace #topic with anchor tags pointing to twitter search api.

This is the javascript needed to convert a tweet in plain text to that containing proper links, hashtags and @ operators.

function tweetify(text) {
text = text.replace(/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0- 9.\-]+[.][a-z]{2,4}\/)(?:(?:[^\s()<>.]+[.]?)+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi, "<a target=_blank href=$1>$1</a>");
text = text.replace(/[\@]+([A-Za-z0-9-_]+)/gi, "<a target=_blank href=http://twitter.com/$1>@$1</a>");
return text.replace(/(?:^| )[\#]+([A-Za-z0-9-_]+)/gi, "<a target=_blank href=http://search.twitter.com/search?q=&tag=$1&lang=all>#$1</a>");
}

No comments: