Skip to main content

Client Side Tweet Parser in JavaScript (jQuery)

Posted in

I just published a simple JavaScript that helps websites comply with Twitter's Display Guidelines. It helps you comply with issues 2,3,4.

It automatically links to urls, hashtags and mentioned usernames. You simply set the div class to 'tweet' (or whatever you change it to in the code) and link to twitter.js. Make sure you also have jQuery(Only tested 1.6.4) loaded before twitter.js. It is a dependency.

https://github.com/kevinohashi/TweetParserJS

Thanks go to Raphael Mudge who helped with some of the regular expressions.

Future improvements: this code isn't perfect by any means. One improvement would be merging the 3 primary functions into one and some conditions. I've also seen some very elegant server side solutions using almost entirely regular expressions from CodeIgniter (see code below).


function parse_tweet($tweet)
{
$search = array('|(http://[^ ]+)|', '/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '/(^|[^a-z0-9_])#([a-z0-9_]+)/i');
$replace = array('$1', '$1@$2', '$1#$2');
$tweet = preg_replace($search, $replace, $tweet);

return $tweet;
}