Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter text js , not calculating the length from text which contains urls with #!

I am using Twitter text js to calculate length of text with urls containing #!. eg:

"Some text http://domain.com#!/path/p/56319216 #tag1 #tag2".

In firefox debugger error generates on this line in twitter text js

 twttr.txt.regexen.extractUrl.exec(text);

No specific error is logged instead my page freezes and alert me to stop the script, please help.

like image 379
Dharmendra Avatar asked Dec 11 '15 13:12

Dharmendra


1 Answers

A pull request as been merged on the github repository on 2012-05-31 introducing the twttr.txt.getTweetLength(text, options) function that is taking consideration to t.co URLs and defined as follow :

twttr.txt.getTweetLength = function(text, options) {
if (!options) {
    options = {
        short_url_length: 22,
        short_url_length_https: 23
    };
}
var textLength = text.length;
var urlsWithIndices = twttr.txt.extractUrlsWithIndices(text);

for (var i = 0; i < urlsWithIndices.length; i++) {
    // Subtract the length of the original URL
    textLength += urlsWithIndices[i].indices[0] -urlsWithIndices[i].indices[1];

    // Add 21 characters for URL starting with https://
    // Otherwise add 20 characters
    if (urlsWithIndices[i].url.toLowerCase().match(/^https:\/\//)) {
        textLength += options.short_url_length_https;
    } else {
        textLength += options.short_url_length;
    }
}

return textLength;
};

So your function will just become :

function charactersleft(tweet) {
return 140 - twttr.txt.getTweetLength(tweet);
}

Plus, regarding the best practices with t.co we should retrieve the short_url_length and short_url_length_https values from twitter and pass them as the options parameter in the twttr.txt.getTweetLength function :

Request GET help/configuration once daily in your application and cache the "short_url_length" (t.co's current maximum length value) for 24 hours. Cache "short_url_length_https" (the maximum length for HTTPS-based t.co links) and use it as the length of HTTPS-based URLs. Especially knowing that some changes in the t.co urls length will be effective on 2013-02-20 as described in the twitter developer blog

like image 134
Ram Ki Avatar answered Nov 06 '22 01:11

Ram Ki