Good quality JavaScript

11th January 2011 by Jason C. Filed under: Web-development

Hmmm, it seems that it’s been an inexcusably long time since I last posted here. Sorry about that, but life gets in the way. I’d rather be too busy to post than not.

Anyway, I ready this a while ago and have just got round to posting it here. It’s an article – Essentials of writing high quality JavaScript. A very useful article with some good pointers on code formatting with analysis of the why. I have changed my curly-brace style as a result, you will be excited to hear. So now I do this:

function somename() {
    // code
}

instead of this

function somename2()
{
   // code
}

Twitter status text links made clickable

23rd February 2010 by Jason C. Filed under: Code-bits

A new design agency being formed by an existing client needed a site. They had a good design ready, I just had to build the thing. It’s built in WordPress, but I also pull in their Twitter stream on the client side.

Twitter’s api is easy enough to use. I opted for the JSON-p format, but something I didn’t realise at the time was that the status updates are purely the plain text. So any URLs, usernames or hashtags are just plain text: no wrapping in <a></a> tags. It’s an easy problem to solve, though, and here it is for anyone else who needs it.

function twitify( text )
{
    // replace urls with linked ones
    var t2 = text.replace(/(http|https)(:\/\/)([^ ]+)/ig, '<a href="$1$2$3">$1$2$3</a>' );

    // replace @username with clickable twitter link
    t2 = t2.replace(/@([^ ]+)/gi,'<a href="http://twitter.com/$1">@$1</a>');

    // replace hashtags with Twitter searches
    t2 = t2.replace(/#([^ ]+)/gi,'<a href="http://search.twitter.com/search?q=%23$1">#$1</a>');

    return t2;
}

So, feed the tweet into that function, and back out it comes with links, @users and #hastags made clickable.

Did I mention I ♥ regular expressions?