Last active
December 14, 2015 08:19
-
-
Save kalmanolah/5056741 to your computer and use it in GitHub Desktop.
A simple Javascript function that linkifies a tweet object's text based on that tweet's 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
/** | |
* A simple Javascript function that linkifies a tweet object's text based on that tweet's entities. | |
* | |
* More info about Tweet Entities: https://dev.twitter.com/docs/tweet-entities . | |
* | |
* NOTE: You may need to add "include_entities=1" or "include_entities=true" to your API request. | |
*/ | |
function linkifyTweet(tweet){ | |
if(!tweet.entities){ | |
return tweet.text; | |
} | |
var container = cache = {}; | |
for(var i=0;i<tweet.entities.hashtags.length;i++){ | |
cache = tweet.entities.hashtags[i]; | |
container[cache.indices[0]] = [cache.indices[1], '<a href="https://twitter.com/search?q='+cache.text+'">#'+cache.text+'</a>']; | |
} | |
for(var i=0;i<tweet.entities.user_mentions.length;i++){ | |
cache = tweet.entities.user_mentions[i]; | |
container[cache.indices[0]] = [cache.indices[1], '<a href="https://twitter.com/'+cache.screen_name+'">@'+cache.screen_name+'</a>']; | |
} | |
for(var i=0;i<tweet.entities.urls.length;i++){ | |
cache = tweet.entities.urls[i]; | |
container[cache.indices[0]] = [cache.indices[1], '<a href="'+cache.url+'">'+(cache.display_url||cache.url)+'</a>']; | |
} | |
var orig = tweet.text; | |
cache = orig; | |
for(var i=0;i<tweet.text.length;i++){ | |
if(container[i]){ | |
cache = cache.replace(orig.substring(i, container[i][0]), container[i][1]); | |
} | |
} | |
return cache; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment