jQuery/regex snippet for Twitter markup

I just implemented fetching and displaying one’s Twitter feed in my feed reader (that I will be inviting people to use when/if I ever feel like it’s finished).

Anyway, today I put in place some regexes that will setup these norms I’ve noticed in other Twitter readers, like @name should link to the person’s twitter page, #jquery should link to a search on Twitter for the word “jquery” and links should of course be href’d to their targets.

Below is the result which seems to be working OK so far:

$(".twitter_row > p").each(function(){
	$(this).html( 
	  $(this).html().
	  replace(/http:\/\/\S+/g,  '<a href="$&" target="_blank">$&</a>').
	  replace(/\s(@)(\w+)/g,    ' @<a href="http://twitter.com/$2" target="_blank">$2</a>').
	  replace(/\s(#)(\w+)/g,    ' #<a href="http://search.twitter.com/search?q=%23$2" target="_blank">$2</a>').
	  replace(/^\w+/,           '<a href="http://twitter.com/$&" target="_blank">$&</a>') 
	);
});

First we anchor tag all URLs, then we link @name to his Twitter page, next we do the search thing with #whatever, not much different this one from the @ stuff.

$& will contain the whole match, $2 will contain the second matched sub-expression, in this case (\w+) which is simply all word characters after the initial @/#.


Finally we tag the first word to link to the twitter page of the updater. Since we know we will always have name: a the start of the string we can use the \s at the beginning of the @ and # regexes, because the string will never start with @something or #something. Thus we eliminate that edge scenario.

Note that in the image I had not yet added the first space before the @<a href… replacement string.

Update: The Twitter API wiki is wrong, at least when it comes to the default behavior of curl on my Unbuntu 9.04 system, this is what works when you want to POST to twitter:

curl -d "" -u username:password http://twitter.com/favorites/create/3090013047.json

If you don’t do that -d “” thing in the beginning curl will do a REQUEST which is not what we want, if it’s lacking you’re going to get something like “This method requires a POST” back.

Related Posts

Tags: , ,