Skip to content

Instantly share code, notes, and snippets.

@dcpesses
Forked from wadey/twitter-entities.js
Last active December 12, 2015 07:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcpesses/4734740 to your computer and use it in GitHub Desktop.
Save dcpesses/4734740 to your computer and use it in GitHub Desktop.
/*
* twitter-entities.js
* This function converts a tweet with "entity" metadata
* from plain text to linkified HTML.
*
* See the documentation here: http://dev.twitter.com/pages/tweet_entities
* Basically, add ?include_entities=true to your timeline call
*
* Based off existing code from Wade Simmons
* Licensed under the MIT license
* http://wades.im/mons
*
* Requires jQuery
*
*/
function has_entities(entities) {
if (!entities) return false;
for (var entity in entities) {
if (entity.length>0) return true;
}
return false;
};
function escapeHTML(text) {
return $('<div/>').text(text).html();
};
function linkify_entities(tweet) {
var index_map = {}, result="", last_i=0, i=0;
// return w/o any processing if no entities passed
if (!has_entities(entities)) {
return escapeHTML(tweet);
}
if (entities.urls) {
$.each(entities.urls, function(i, entry) {
index_map[entry.indices[0]] = [entry.indices[1], function(text) {
return "<a href='" + escapeHTML(entry.url) + "' title='" + escapeHTML(entry.expanded_url) + "'>" + escapeHTML(entry.display_url) + "</a>";
}];
});
}
if (entities.media) {
$.each(entities.media, function(i, entry) {
index_map[entry.indices[0]] = [entry.indices[1], function(text) {
return "<a href='" + escapeHTML(entry.url) + "' title='" + escapeHTML(entry.expanded_url) + "'>" + escapeHTML(entry.display_url) + "</a>";
}];
});
}
if (entities.hashtags) {
$.each(entities.hashtags, function(i, entry) {
index_map[entry.indices[0]] = [entry.indices[1], function(text) {
return "<a href='http://twitter.com/search?q=" + escape("#" + entry.text) + "'>" + escapeHTML(text) + "</a>";
}];
});
}
if (entities.user_mentions) {
$.each(entities.user_mentions, function(i, entry) {
index_map[entry.indices[0]] = [entry.indices[1], function(text) {
return "<a title='" + escapeHTML(entry.name) + "' href='http://twitter.com/" + escapeHTML(entry.screen_name) + "'>" + escapeHTML(text) + "</a>";
}];
});
}
// iterate through the string looking for matches in the index_map
for (i = 0; i < tweet.length; i++) {
var ind = index_map[i];
if (ind) {
var end = ind[0], func = ind[1];
if (i > last_i) {
result += escapeHTML(tweet.substring(last_i, i));
}
result += func(tweet.substring(i, end));
i = end - 1;
last_i = end;
}
}
if (i > last_i) {
result += escapeHTML(tweet.substring(last_i, i));
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment