Friday 22 July 2011

A javascript for reconizing a URL in text and linkifying it

On a similar theme to the one below. here is a JS function that will linkify any http:\\ in a text strream for you

String.prototype.linkify = function() 
   var url1 = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g
   var url2 = /(^|<|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|>|$)/g
   var myresult = myresult.replace(/&/g, '&')
                         .replace(/</g, '&lt;')
                         .replace(/>/g, '&gt;')
                         .replace(url1, '$1<a target="_blank" href="http://$2">$2</a>$3')
                         .replace(url2, '$1<a target="_blank" href="$2">$2</a>$5');
   return myresult;

Disqus for Domi-No-Yes-Maybe