javascript获取一个字符串的长度(包含中文)

        /*
        getStrLen(str):获取一个字符串的长度(包含中文)
    */
    function getStrLen(str){
        let len = 0, i, c;
        for (i = 0; i < str.length; i++){
            c = str.charCodeAt(i);
            if((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)){len++;}else{len+=2;}
        }
        return len;
    }
    //调用:
    document.write(getStrLen("HelloWorld"));//10
    document.write(getStrLen("www你好世界"));//17

一个中文字符串的长度等于4

posted @ 2020-02-16 14:34  鸡儿er  阅读(359)  评论(0编辑  收藏  举报