当前位置 : 主页 > 网络编程 > JavaScript >

计算 UTF-8 编码字符串长度

来源:互联网 收集:自由互联 发布时间:2021-06-30
gistfile1.txt /** * Count bytes in a string's UTF-8 representation. * https://codereview.stackexchange.com/a/37552 * @param string * @return int */function getByteLen(normal_val) { // Force string type normal_val = String(normal_val); var b
gistfile1.txt
/**
 * Count bytes in a string's UTF-8 representation.
 * https://codereview.stackexchange.com/a/37552
 * @param   string
 * @return  int
 */
function getByteLen(normal_val) {
    // Force string type
    normal_val = String(normal_val);

    var byteLen = 0;
    for (var i = 0; i < normal_val.length; i++) {
        var c = normal_val.charCodeAt(i);
        byteLen += c < (1 <<  7) ? 1 :
                   c < (1 << 11) ? 2 :
                   c < (1 << 16) ? 3 :
                   c < (1 << 21) ? 4 :
                   c < (1 << 26) ? 5 :
                   c < (1 << 31) ? 6 : Number.NaN;
    }
    return byteLen;
}
网友评论