计算新浪Weibo消息长度

此文为计算新浪Weibo的消息长度的方法. 就是 (发言请遵守社区公约,还可以输入119字).

var getMessageLength = (function() {
	var byteLength = function(b) {
			if(typeof b == "undefined") {
				return 0;
			}
			var a = b.match(/[^\x00-\x80]/g);
			return(b.length + (!a ? 0 : a.length));
		};
	return function(message) {
		message = message || '';
		message = message.replace(/\r\n/g, "\n");
		var c = 41,
			d = 140,
			e = 20,
			f = message,
			g = message.match(/http:\/\/[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+([-A-Z0-9a-z_\$\.\+\!\*\(\)\/,:;@&=\?\~\#\%]*)*/gi) || [],
			h = 0;

		for(var i = 0, j = g.length; i < j; i++) {
			var k = byteLength(g[i]);
			if(/^(http:\/\/t.cn)/.test(g[i])) {
				continue;
			}
			/^(http:\/\/)+(t.sina.com.cn|t.sina.cn)/.test(g[i]) || /^(http:\/\/)+(weibo.com|weibo.cn)/.test(g[i]) ? h += k <= c ? k : k <= d ? e : k - d + e : h += k <= d ? e : k - d + e;
			f = f.replace(g[i], "");
		}
		var l = Math.ceil((h + byteLength(f)) / 2);
		return l;
	};
})();

getMessageLength('昨天电脑的硬盘坏了,我发邮件给美国国家安全局,他们竟然不肯把备份的内容发给我!');    //39

 

posted @ 2013-07-01 17:18  zhongsp  阅读(335)  评论(1编辑  收藏  举报