-
-
Save creativeaura/4024898 to your computer and use it in GitHub Desktop.
Linkify Twitter API entities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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