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.

tags: / / / / / /

1 comments

  • Thomas Schmidt

    Posted: Dec 2, 2011

    I searched one hour for that expression. It works great. Thanks.

    Hope it will do it even if the spacer at the end is strange like a tab or a bracket.

"w3fools.com - because friends don't let friends use w3schools" ~ dan heberden
themify
Learning JavaScript