JavaScript 字符串字节数判断方法
在 JavaScript 中,可以通过以下方法来判断一个字符串的字节数:
- 使用字符串的 'length' 属性得到字符串的字符数,然后乘以 2 得到字符串的字节数。
let str = 'hello world';
let bytes = str.length * 2;
console.log(bytes);
- 使用 TextEncoder API 将字符串编码成一个 Uint8Array 类型的数组,然后得到该数组的字节数。
let str = 'hello world';
let encoder = new TextEncoder();
let bytes = encoder.encode(str).length;
console.log(bytes);
- 使用 'encodeURIComponent' 方法将字符串进行 URL 编码,然后得到编码后的字符串的字节数。
let str = 'hello world';
let encoded = encodeURIComponent(str);
let bytes = encoded.length * 2;
console.log(bytes);
需要注意的是,以上方法都只能得到一个字符串的字节数,如果需要判断一个字符串数组的总字节数,需要遍历数组并累加每个字符串的字节数。
原文地址: https://www.cveoy.top/t/topic/lDqW 著作权归作者所有。请勿转载和采集!