Darcy ClarkeDevelopment / Design / UX

Toggle Main Navigation

Apr 5, 2011

Make Text URLs Active - Javascript/jQuery

Posted in "development"


I've come across this many times where I want to be able to turn static text URL's into active HTML links with Javascript. A long time ago I came across a script for it and have been using it alongside jQuery. The solution is essentially using some good old Javascript and Regular Expressions. Here's the snippet:

var exp = /(b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig;
$('body').html($('body').html().replace(exp,"<a href='$1'>$1</a>"));

It should be noted that you won't want to use the .replace() on your entire document or body element if you've got pre-existing active links. If you do, it may cause a conflict and duplicate the HTML link syntax. With that said, be specific with your selectors that will be used to find and replace static urls.