juankennaugh
5/19/2015 - 9:00 PM

linkify.js

/* 
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;
};