Skip to content

Instantly share code, notes, and snippets.

@jaggy
Created June 23, 2016 06:48
Show Gist options
  • Select an option

  • Save jaggy/bd4762d1ae01a3ee0d7e480d0476795b to your computer and use it in GitHub Desktop.

Select an option

Save jaggy/bd4762d1ae01a3ee0d7e480d0476795b to your computer and use it in GitHub Desktop.
function replace_links(tweet) {
var pattern = /(http[s:\/a-zA-Z0-9\.\_]+)\b/gm;
return tweet.replace(pattern, '<a href="$1">$1</a>');
}
function replace_mentions(tweet) {
var pattern = /(\@(.+?))\b/gm;
var base_url = 'https://twitter.com/';
return tweet.replace(pattern, '<a href="' + base_url + '$2">$1</a>');
}
function replace_hashtags(tweet) {
var pattern = /(\#(.+?))\b/gm;
var base_url = 'https://twitter.com/hashtag/';
return tweet.replace(pattern, '<a href="' + base_url + '$2">$1</a>');
}
/**
* Build the tweet by parsing the hashtags, mentions, and the links
* of the tweet.
*
* The order of precedence is quite specific only becase we don't want to
* rereplace the links provided by the hashtag replacer and the mention replacer.
*
* Just make sure we replace the links before we replace everything else.
*
* @param string tweet
* @return string
*/
function build_tweet(tweet) {
return replace_mentions(replace_hashtags(replace_links(tweet)));
}
var sample_tweet = "@CrisisGroup again misses the point! We're tiered of hearing recycled stories meant to serve the hunter's story. https://t.co/TrWX9kWfos #HashTag @CrisisGroup #icg https://t.co/IAmAUrl";
console.log(build_tweet(sample_tweet));
// https://twitter.com/hashtag/tribezparty?src=hash
// ((\@.+?)\b|(\#.+?)\b|(http[s:\/a-zA-Z0-9\.\_]+)\b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment