Javascript: Parse Twitter Usernames, Hashtags and URIs

July 28, 2010

Twitter provides a plain-text stream of tweets. I was looking to add links to this stream for the usernames, URIs, and hashes. I wound up with the following function that hopefully you will find useful.

function parseTwitter(text) {
        // Parse URIs
        text = text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(uri) {
		return uri.link(uri);
	});

        // Parse Twitter usernames
        text = text.replace(/[@]+[A-Za-z0-9-_]+/, function(u) {
		var username = u.replace("@","")
		return u.link("http://twitter.com/"+username);
	});
	
	// Parse Twitter hash tags
	text = text.replace(/[#]+[A-Za-z0-9-_]+/, function(t) {
		var tag = t.replace("#","%23")
		return t.link("http://search.twitter.com/search?q="+tag);
	});
        return text;
}

To use it simply toss in any string with a Twitteresque format and viola, links!