//字节长度,双字节为2
CHRD.byteLen = function (str) {
return 'string' == typeof str ? str.replace(/[^x00-\xff]/g, '00').length : (str && str.length);
}
//字节截取,start与len都是按单字节算,开始如果是半个中文,就取整个中文,len是半个中文,就不取此中文,开始从0开始,不允许负值
CHRD.byteSub = function (str, start, len, more) {
start = start > 0 ? start : 0;
len = len > 0 ? len : null;
var byteL = 0;
var sub = '';
for (var i = c = cl = 0; i < str.length; i++) {
c = str.charCodeAt(i);
cl = c > 0xff ? 2 : 1;
byteL += cl;
if (start >= byteL) {//还不到开始位
continue;
}
if (
(len == null) //取完
|| ((len -= cl) >= 0) //取本字时不超过
) {
sub += String.fromCharCode(c);
} else {//取超了
more && (sub += more);
break;
}
}
return sub;
}
js:单字节(英文一个,中文二个)长度/截取(substr)实现
最新推荐文章于 2022-01-20 10:45:26 发布