Skip to content

Instantly share code, notes, and snippets.

@danwaz
Last active October 7, 2015 20:17
Show Gist options
  • Save danwaz/3219505 to your computer and use it in GitHub Desktop.
Save danwaz/3219505 to your computer and use it in GitHub Desktop.
Format Tweet
/*
* Dan Wasilewski
*
* A simple function that formats a tweet's text to include linked entities (hashtag, mentions, and links)
* When fetching tweets, make sure to add include_entities=1 to your query string
*
*/
var formatTweet = function(tweetObj){
//create an array of tweet entities
var tweetArr = [],
formattedText = tweetObj.text;
for (var entity in tweetObj.entities){
if(typeof tweetObj.entities[entity] !== 'function'){
for (var i = 0; i < tweetObj.entities[entity].length; i++){
tweetArr.push(tweetObj.entities[entity][i]);
}
}
}
//sort index from largest to smallest
tweetArr.sort(function(a,b) { return parseInt(b.indices[0]) - parseInt(a.indices[0]) } );
//format it!
for (var i = 0; i < tweetArr.length; i++){
var toFormat = tweetArr[i],
targetText = formattedText.substring(toFormat.indices[0], toFormat.indices[1]);
if (toFormat.screen_name){
formattedText = formattedText.replace(targetText, '<a href="http://twitter.com/'+ toFormat.screen_name +'" target="_blank">'+ targetText +'</a>');
} else if (toFormat.url){
formattedText = formattedText.replace(targetText, '<a href="'+ targetText +'" target="_blank">'+ targetText +'</a>');
} else {
formattedText = formattedText.replace(targetText, '<a href="http://twitter.com/hashtag/'+ toFormat.text +'" target="_blank">'+ targetText +'</a>');
}
}
return formattedText;
};
var formatTime = function(timeToFormat){
var currentTime = new Date().getTime() / 1000,
timeAgo = currentTime - timeToFormat,
formattedTime = '';
if(timeAgo < 60) {
formattedTime = timeAgo + ' seconds ago';
} else if(timeAgo < 3600) {
formattedTime = Math.floor(timeAgo/60) + (Math.floor(timeAgo/60) == 1 ? ' minute ago' : ' minutes ago');
} else if(timeAgo < 86400) {
formattedTime = Math.floor(timeAgo/3600) + (Math.floor(timeAgo/3600) == 1 ? ' hour ago' : ' hours ago');
} else if(timeAgo > 86400) {
formattedTime = Math.floor(timeAgo/86400) + (Math.floor(timeAgo/86400) == 1 ? ' day ago' : ' days ago');
}
return formattedTime;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment