Twitter文本js,不根据包含带#的URL的文本计算长度

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

本文关键字:文本 URL 计算 js Twitter 包含带      更新时间:2023-09-26

我使用Twitter文本js计算URL包含#!的文本长度!。例如:

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

在firefox中,调试器在twitter文本js 中的这一行生成错误

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

没有记录任何特定的错误,而是我的页面冻结并提醒我停止脚本,请帮助。

2012-05-31在github存储库上合并的拉取请求引入了twttr.txt.getTweetLength(文本,选项)函数,该函数考虑了t.co URL,定义如下:

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

所以你的功能将变成:

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

此外,关于t.co的最佳实践,我们应该从twitter中检索short_url_length和short_url_length_https值,并将它们作为twttr.txt.getTweetLength函数中的选项参数传递:

每天在应用程序中请求一次GET帮助/配置,并将"short_url_length"(t.co当前的最大长度值)缓存24小时。缓存"short_url_length_https"(基于https的t.co链接的最大长度),并将其用作基于https的url的长度。特别是知道t.courls长度的一些更改将在2013-02-20生效,如twitter开发者博客

中所述