JS计算字符串所占字节数

in 前端 with 0 comment
const sizeof = (str, charset = 'utf8') => {
  let total = 0,
      charCode,
      i,
      len;
  charset = charset ? charset.toLowerCase() : '';
  if (charset === 'utf-16' || charset === 'utf16') {
    for (i = 0, len = str.length; i < len; i++) {
      charCode = str.charCodeAt(i);
      if (charCode <= 0xffff) {
        total += 2;
      } else {
        total += 4;
      }
    }
  } else {
    for (i = 0, len = str.length; i < len; i++) {
      charCode = str.charCodeAt(i);
      if (charCode <= 0x007f) {
        total += 1;
      } else if (charCode <= 0x07ff) {
        total += 2;
      } else if (charCode <= 0xffff) {
        total += 3;
      } else {
        total += 4;
      }
    }
  }
  return total;
}

主要是EOS DAPP开发的memo不能超过256bytes,这个可以用来在浏览器端计算memo长度

参考:http://www.alloyteam.com/2013/12/js-calculate-the-number-of-bytes-occupied-by-a-string/

Comments are closed.