Created
November 20, 2009 16:50
-
-
Save polotek/239619 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Autolink urls in text | |
* Optionally autolink usernames and hashtags in twitter text | |
*/ | |
function autolink(txt){ | |
if(!txt) return; | |
var txtstr = txt + ''; //make sure it's a string | |
var url_re = /(http(s)?:\/\/[^\s)]+)/ig; | |
return txtstr.replace(url_re, '<a href="$1" target="_blank" rel="nofollow">$1</a>') || txt; | |
} | |
function autolink_twitter(txt){ | |
txt = autolink(txt); | |
var txtstr = txt + ''; //make sure it's a string | |
var re = /(^|\W)(@([a-z0-9_]+[a-z0-9_-]*))/ig; | |
txtstr = txtstr.replace(re, '$1<a href="http://twitter.com/$3" target="_blank" rel="nofollow">$2</a>'); | |
var txtarr = txtstr.split(' '); | |
re = /(^|\W)(#([\w]+))/i; | |
var outarr = []; | |
var m = null; | |
for(var i=0; i<txtarr.length;i++) { | |
m = txtarr[i].match(re); | |
if(!m || m.length < 2) { | |
outarr[outarr.length] = txtarr[i]; | |
continue; | |
} | |
var n = '<a href="http://search.twitter.com/search?tag=' + encodeURIComponent(m[3]) + '" target="_blank" rel="nofollow">' + m[2] + '</a>'; | |
outarr[outarr.length] = txtarr[i].replace(re, '$1'+n); | |
} | |
return (outarr && outarr.length) ? outarr.join(' ') : txt; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment