Wrap URLs in anchors

by Michel Plungjan

JavaScript

// the {1} is to handle this bug: blog.stevenlevithan.com/archives/regex-lookahead-bug
var regex = /(http|ftp|https:\/\/[\w\-_]+\.{1}[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/gi;

function WrapAnchorTag(text) {
    return text.replace(regex,'<a href="$1$2" target="_blank">$1$2</a>');
}

var str = "some text with link http://www.google.com link http://plungjan.name/ and some more http://google.com/search?q=regex+url"
document.write('<hr/>'+str+'<br/>'+WrapAnchorTag(str));