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) {

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *