Skip to content

Instantly share code, notes, and snippets.

@JakeCoxon
Created April 22, 2012 15:29
Show Gist options
  • Save JakeCoxon/2464656 to your computer and use it in GitHub Desktop.
Save JakeCoxon/2464656 to your computer and use it in GitHub Desktop.
Replaces url entities in a string received from Twitter API
var linkify = (function() {
var replaceSubstr = function(text, i, j, substr) {
return text.substr(0, i) + substr + text.substr(j);
}
var mergeByIndices = function(a, b) {
var i = 0, j = 0, result = [];
while (i < a.length || j < b.length) {
if (i < a.length && (j >= b.length || a[i].indices[0] < b[j].indices[0]))
result.push(a[i++]);
else
result.push(b[j++]);
}
return result;
}
var linkEntity = function(entity) {
if (entity.name) // user mention
return "<a href=\"http://twitter.com/"+entity.screen_name+"\" class=\"user-mention\">@"+entity.screen_name+"</a>";
else if (entity.url) // url
return "<a href=\""+entity.url+"\" class=\"url\">"+entity.display_url+"</a>";
else // hashtag
return "<a href=\"http://twitter.com/search/%23"+entity.text+"\" class=\"hashtag\">#"+entity.text+"</a>";
}
var linkify = function(post) {
var text = post.text, offset = 0;
var entities = mergeByIndices(mergeByIndices(post.entities.hashtags, post.entities.urls), post.entities.user_mentions);
$.each(entities, function(i, entity) {
var new_substr = linkEntity(entity);
text = replaceSubstr(text, entity.indices[0] + offset, entity.indices[1] + offset, new_substr);
offset += new_substr.length - (entity.indices[1] - entity.indices[0]);
});
return text;
}
return linkify;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment