xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

vanilla js get string's bytes length All In One

vanilla js get string's bytes length All In One

Blob

new Blob(["😀"]).size;
// 4

new Blob(["👻"]).size;
// 4

new Blob(["🇨🇳"]).size;
// 8

unicode

// 计算字符长度(中英文)

const getByteLen = (val) => {
    let len = 0;
    for (let i = 0; i < val.length; i++) {
        let a = val.charAt(i);
        if (a.match(/[^\x00-\xff]/ig) != null) {
            len += 2;
        } else {
            len += 1;
        }
    }
    return len;
};

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-08-11 21:22  xgqfrms  阅读(78)  评论(4编辑  收藏  举报