JavaScript 字符串字节长度判断方法
可以使用以下方法来判断字符串的字节长度:
- 使用 'TextEncoder' API
const encoder = new TextEncoder();
const byteLength = encoder.encode(str).length;
- 使用 'Blob' API
const blob = new Blob([str]);
const byteLength = blob.size;
- 使用 'encodeURIComponent' 和 'decodeURIComponent'
const byteLength = encodeURIComponent(str).replace(/%[A-F\d]{2}/g, 'U').length;
注意:以上方法都只能用于 ASCII 字符集,对于非 ASCII 字符集的字符串可能会得到错误的结果。
原文地址: https://www.cveoy.top/t/topic/lDqV 著作权归作者所有。请勿转载和采集!