在javascript中,一個字母和數字佔一個字節,中文佔兩個字節。可以測試一下:
console.log('abcd1234'.length);//8 console.log('我的博客'.length);//4
因此,假如要計算一個字符串的字節長度,就要區分是否是中文。
我想到的有兩種方法:
1、將中文用兩個英文字符替換,比如用"**"替換,然後計算str.lenght;
2、除了中文,其它字符,比如字母,數字,符號等都是屬於ascii碼,
所以charCode應該在0-255之間,如果大於255,那麼str.length++即可。
代碼實現如下:
//方法一 function getBytes(str){ str = str.replace(/[^\x00-\xff]/g, '**');//將非ascii碼轉換爲2個ascii碼 return str.length; }
方法二:
function getBytes(str){ var bytes= str.length; for(var i = bytes; i--;){ if(str.charCodeAt(i) > 255){ bytes++; } } return bytes; }