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

1

11

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.

Waynant answered 11/12, 2015 at 13:9 Comment(3)
If you want to calculate length of text then why not simply text.length?Mikkimiko
@Mikkimiko Twitter wraps all urls in a tweet to t.co short urls. So I need to calculate length of tweet before sending to Twitter.Waynant
Are you using the latest version from here github.com/twitter/twitter-text/tree/master/js/pkg ?Coleslaw
G
5

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

Gosport answered 14/12, 2015 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.