Skip to content

Instantly share code, notes, and snippets.

@fffergal
Created November 27, 2009 01:24
Show Gist options
  • Save fffergal/243765 to your computer and use it in GitHub Desktop.
Save fffergal/243765 to your computer and use it in GitHub Desktop.
function anchorify(text) {
var URIregex=/\b(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?(?:(?:[-\w]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?\b/g;
var returnArray=[];
while (true) {
var previousLastIndex=URIregex.lastIndex;
var URImatch=URIregex.exec(text);
if (URImatch == null) {
returnArray.push(text.substr(previousLastIndex,text.length-previousLastIndex));
return returnArray;
}
returnArray.push(text.substr(previousLastIndex,URImatch.index-previousLastIndex));
if (text.substr(URImatch.index-1,1) == '@') {
returnArray.push(URImatch[0]);
}
else {
var newURI=(URImatch[0].substr(0,6) == 'ftp://' || URImatch[0].substr(0,7) == 'http://' || URImatch[0].substr(0,8) == 'https://') ? URImatch[0] : 'http://' + URImatch[0];
var newAnchor=new Element('a',{href:newURI,style:'text-decoration:underline;'});
newAnchor.appendChild(document.createTextNode(URImatch[0]));
returnArray.push(newAnchor);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment