js:单字节(英文一个,中文二个)长度/截取(substr)实现


//字节长度,双字节为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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值