addLinks() - find URLs in a piece of text
This snippet take a block of text and an element name and returns an element of that type with the text in it and all URLs turned into a-hrefs:
function addLinks(text, tagName){
var urlRE = /(http:[\;\/\?\\@\&\=\+\$\,\[\]A-Za-z0-9\-_\.\!\~\*\'\(\)%][\;\/\?\:\@\&\=\+\$\,\[\]A-Za-z0-9\-_\.\!\~\*\'\(\)%#]*)/g;
var cruft = /([\]\)\,\.\'\"\;]+)$/;
var span = document.createElement(tagName);
var c = 0;
text.replace(urlRE, function(m,a1,p){
// Add the text that occurred between our last result and this one as plain text
span.appendChild(document.createTextNode(text.substring(c,p)));
a1 = a1.replace(cruft,'');
c=p+a1.length;
// Add the URL as an a-href
var a = document.createElement('a');
a.href = a1;
a.appendChild(document.createTextNode(a1));
span.appendChild(a);
});
if(text.substr(c))
span.appendChild(document.createTextNode(text.substr(c)));
return span;
}
Original code by Woosta -- posted 2008-03-22
Regex taken from perl's URI::Find