Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
linkify @mentions and #hashtags in a tweet
function(a){return a.replace(/[@#]\w+/g,function(b,c){a="search";c="";return"//"+(b[a]("#")?c:a+"."+c+a+"?q=")+b)})}

Pet3ris commented May 25, 2011

This should be a byte shorter:

function(a){return a.replace(/[@#]\w+/g,function(b,c){c="";return"//"+(b[a="search"]("#")?c:a+"."+c+a+"?q=")+b)})}

jed commented May 25, 2011

Good catch! Fixed. That byte may be what we need to fix @mention links from including the @.

Awesome work Jed, although I have some changes:

  1. It matches email address too, so need \B to indicate a word boundary
  2. It contains the @ in the mention URL (which works, but it isn't perfect)

I've made some changes to fix these issues and it comes in at 138 bytes:

function(a){return a.replace(/\B[@#]\w+/g,function(b){return'//'+(b[a='search']('#')?'':a+'?q=%23')+b.substring(1))})}

jed commented Aug 5, 2011

ha, who tweets email addresses?

(but seriously, thanks! fixed.)

maettig commented Nov 15, 2011

You need to use \B instead of \b. \b matches boundaries where a word and a non-word character met (or vice versa). For example, ''.replace(/\b/g,'|') returns |example|@|example|.|com|, making all boundaries visible. In your case, you need it the other way around. There should not be a boundary in front of the @. Hope that helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment