Skip to content

Instantly share code, notes, and snippets.

@briancray
Created November 6, 2012 13:56
Show Gist options
  • Save briancray/4024871 to your computer and use it in GitHub Desktop.
Save briancray/4024871 to your computer and use it in GitHub Desktop.
Linkify Twitter API entities
/*
Compliant with Twitter's Developer Display Requirements:
https://dev.twitter.com/terms/display-requirements
*/
var linkify_result = function (tweet /* tweet object from the results array */) {
var subs = [],
last_offset = 0,
new_tweet = '',
entity,
replace = {
hashtags: function (text) {
return '<a href="https://twitter.com/search?q=%23' + text + '">#' + text + '</a>';
},
media: function (text) {
return '<a href="' + text[0] + '">' + text[1] + '</a>';
},
urls: function (text) {
return '<a href="' + text[0] + '">' + text[1] + '</a>';
},
user_mentions: function (text) {
return '<a href="https://twitter.com/' + text + '">@' + text + '</a>';
}
};
for (entity in tweet.entities) {
tweet.entities[entity].forEach(function (d, i) {
subs.push([
entity,
d.indices,
d.text ? d.text :
d.display_url ? [d.url, d.display_url] :
d.screen_name
]);
});
}
subs.sort(function (a, b) {
return a[1][0] - b[1][0];
});
subs.forEach(function (d, i) {
new_tweet += tweet.text.slice(last_offset, d[1][0]);
new_tweet += replace[d[0]](d[2]);
last_offset = d[1][1];
});
new_tweet += tweet.text.slice(last_offset);
return new_tweet;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment