Posted By

troynt on 03/28/09


Tagged

regex javascript


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

romainsauger
anniemughal


Convert Text URLs into Links


 / Published in: JavaScript
 

  1. linkify_plain:function(text)
  2. {
  3. if( !text ) return text;
  4.  
  5. text = text.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,function(url){
  6. nice = url;
  7. if( url.match('^https?:\/\/') )
  8. {
  9. nice = nice.replace(/^https?:\/\//i,'')
  10. }
  11. else
  12. url = 'http://'+url;
  13.  
  14.  
  15. return '<a target="_blank" rel="nofollow" href="'+ url +'">'+ nice.replace(/^www./i,'') +'</a>';
  16. });
  17.  
  18. return text;
  19. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Sephr on March 29, 2009

You do know that that's not valid javascript and will cause an error? Don't just copy/paste some code from a script and expect it to work. Replace linkify_plain:function(text) with function linkify_plain(text)

Posted By: troynt on April 8, 2009

Sorry I was using it in the context of...

object = { linkify_plain:function(text) { //code here } }

Posted By: MaRmAR on December 12, 2010

This function works OK, but actually it will replace all links including links in tags (IMG, existing A HREFs, STYLE etc.)

You need to login to post a comment.