/** 统计字节长度 str 要统计的字符串 cnCharByteLen 中文字节长度 */ function countByteLength(str, cnCharByteLen) { var byteLen = 0; for (var i=0; i<str.length; i++) { if ((/[\x00-\xff]/g).test(str.charAt(i))) byteLen += 1; else byteLen += cnCharByteLen; } return byteLen; }
范例:
var str = '汉字AA'; var len = countByteLength(str, 2); #输出 len 等于 6 var str = '汉字AA'; var len = countByteLength(str, 1); #输出 len 等于 4 在开发中会遇到一个汉字算一个字符的情况,这时可以把第二个参数设为1