Skip to content

Instantly share code, notes, and snippets.

@jed
Forked from 140bytes/LICENSE.txt
Created May 9, 2011 16:22
Show Gist options
  • Save jed/962823 to your computer and use it in GitHub Desktop.
Save jed/962823 to your computer and use it in GitHub Desktop.
linkify @mentions and #hashtags in a tweet
function(
a // the text of the tweet to be enlinked
){
return a.replace( // replace
/\b[@#]\w+/g, // any mention/hashtag
function(
b, // the matched mention/hashtag
c // placeholder
){
c = "twitter.com/"; // the core twitter url
return b.link( // put the match in a link to
"//" + ( // the "//" protocol, +
b[a = "search"] // match the url, reusing for "search"
("#") // if the match starts with "#"
? c // twitter.com/, or otherwise
: a + "." + c + // search.twitter.com/ +
a + "?q=" // search?q=
) + // and then finally, +
b // the mention/hashtag.
)
}
)
}
function(a){return a.replace(/\b[@#]\w+/g,function(b,c){c="twitter.com/";return b.link("//"+(b[a="search"]("#")?c:a+"."+c+a+"?q=")+b)})}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Jed Schmidt <http://jed.is>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "enlink",
"keywords": ["twitter", "tweet", "link", "mention", "hashtag"]
}
@jamiebicknell
Copy link

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.link('//twitter.com/'+(b[a='search']('#')?'':a+'?q=%23')+b.substring(1))})}

@jed
Copy link
Author

jed commented Aug 5, 2011

ha, who tweets email addresses?

(but seriously, thanks! fixed.)

@maettig
Copy link

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, '[email protected]'.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