Permalink
Browse files

Merge pull request #58 from twitter/tweet_length

Modify tweet_length to count URL as 20/21 chars
  • Loading branch information...
Keita Fujii
Keita Fujii committed May 31, 2012
2 parents 39d5b1d + 3f3d5e6 commit c469e31c541ed5bd66b9765c1d31da510d329950
Showing with 33 additions and 1 deletion.
  1. +4 −0 test/conformance.html
  2. +29 −1 twitter-text.js
View
@@ -117,6 +117,10 @@
return function(test) {
return twttr.txt.isValidUrl(test.text, true, false);
};
+ case "lengths":
+ return function(test) {
+ return twttr.txt.getTweetLength(test.text);
+ };
}
}
View
@@ -1059,6 +1059,33 @@ if (typeof twttr === "undefined" || twttr === null) {
fromCode(0x202E)
];
+ // Returns the length of Tweet text with consideration to t.co URL replacement
+ twttr.txt.getTweetLength = function(text, options) {
+ if (!options) {
+ options = {
+ short_url_length: 20,
+ short_url_length_https: 21
+ };
+ }
+ 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;
+ };
+
// Check the text for any reason that it may not be valid as a Tweet. This is meant as a pre-validation
// before posting to api.twitter.com. There are several server-side reasons for Tweets to fail but this pre-validation
// will allow quicker feedback.
@@ -1073,7 +1100,8 @@ if (typeof twttr === "undefined" || twttr === null) {
return "empty";
}
- if (text.length > MAX_LENGTH) {
+ // Determine max length independent of URL length
+ if (twttr.txt.getTweetLength(text) > MAX_LENGTH) {
return "too_long";
}

0 comments on commit c469e31

Please sign in to comment.