Monday, May 3, 2010

JavaScript: URL's to Clickable Links

HTML is text. I find myself parsing text lots in HTML. It's one of the reasons I'm a fan of perl -- perl does text. Now I have found myself in a position to need to use JavaScript to make actual links out of plain text. Turns out it's pretty simple with a few caveats to follow. Here's the basic code:

var t = 'url http://bobbreedlove.com/livetoad';
var l = t.match(/http\S+/i);
if (l !== null) {
    t = t.replace(l, ''+l+'');
}

"t": any text (note caveats below)
"t.match" uses the RegExp to pick off something that looks like a URL. Note that the "\S" is any non-whitespace character. This function returns the strings which were found to match the pattern. Note that this code assumes that there is only one matching string (e.g. one URL).
The "if" statement checks to make sure that there was something in the string. If not, the original string is left alone.
"t.replace" replaces the matched string "l".with the HTML following the comman in the call to format a clickable link in the original string "t". Note that this particular link uses a "_blank" target to open a new window. Just about anything can be added. One thought would be to apply a unique ID to the link and be able to style it, but, hey, that's another blog.

Caveats:

The Regular Expression assumes that there are no whitespace characters in the URL (e.g. no spaces). It also assumes that the URL is followed by a whitespace character (or the end of the string). If you are using the URL in a sentence and end it with a period, for example, this code would pick up the period.

It's actually pretty simple code. You can see it actually working in the "140 Character Thoughts" block on the Live Toad page on my site. This block retrieves Tweets from Twitter and makes the URL's clickable. Note also that it opens a new window, just to keep people on the site.

Working with text can make your site more dynamic. This technique can be used to construct URL's that actually work as links from plain text. Maybe I'll expand it next to pick up multiple URL's in the text string.

Enjoy!

No comments:

Post a Comment