Create a link from plain text

Hi,

I am using a Twitter plugin which outputs tweets as plain text. I would like to take the usernames and create links to their profiles from the text.

So I would like…

Coffee’s great @WickedCoffeeCo @StuGoulden. Just not when you’re already in a mood.

To become…

Coffee’s great @WickedCoffeeCo [URL=“http://twtiter.com/StuGoulden”]@StuGoulden. Just not when you’re already in a mood.

So I’d like the script to read the text (which will be in a div with an ID of “tweets”) and grab each @username and create

<a href="http://twitter.com/username">@username</a>

Is this possible? jQuery is already running if that helps : )

Many thanks

This solution assumes that you’re using at least jQuery 1.4 (also, here’s a fiddle):


$('#tweet').html(function (i, html) {
    return html.replace(/@([a-z]+)/ig, '<a href="http://twitter.com/$1">@$1</a>');
});

Another huge problem (in my opinion) is that it relies on the innerHTML property, which can cause serious issues on mobile. But that’s more an issue with jQuery itself than this particular script.

Perfect! Thanks so much!! (Love the Fiddle touch as well, inspired)