1. // 字符串中的英文、数字、特殊字符等为一个字节,中文汉字是两个字节
    2. function countByte(str) {
    3. let length = 0;
    4. for (let i = 0; i < str.length; i++) {
    5. // 先看看它是不是双字节
    6. if (/[\u4e00-\u9fa5]/g.test(str[i])) {
    7. length += 2;
    8. } else {
    9. length += 1;
    10. }
    11. }
    12. return length;
    13. }
    14. console.log(countByte('你好hello world'));