js-以字符串长度作为字节长度带来bug

  |  

js编码中 字母和数字占据一个字节,但是有些其他符号占据2,3,4个字节的也有

因此,想要获取字符串的字节长度,就不能单纯的使用String.length

export const mbStringLength = s =>{
var totalLength = 0;
var i;
var charCode;
for(i=0;i<s.length;i++){
charCode = s.charCodeAt(i);
if(charCode < 0x007f){
totalLength +=1;
}else if(0x0080<=charCode && charCode <= ox07ff){
totalLength +=2;
}else if(0x0800 <= charCode && charCode <= 0xffff){
totalLength +=3;
}else{
totalLength +=4;
}
}
retrun totalLength;
}

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
,