public
Last active

Linkify Twitter API entities

  • Download Gist
linkify.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
/*
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;
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.