UNPKG

bbo

Version:

bbo is a utility library of zero dependencies for javascript.

46 lines (38 loc) 956 B
'use strict'; /* eslint-disable */ /** * Returns the length of a string in bytes by Unicode (utf-8 utf8 utf-16 utf16) */ function byteLen(str, charset) { var total = 0; var charCode; if (charset === 'utf-8' || charset === 'utf8') { for (var i = 0, len = str.length; i < len; i++) { charCode = str.codePointAt(i); if (charCode <= 0x007f) { total += 1; } else if (charCode <= 0x07ff) { total += 2; } else if (charCode <= 0xffff) { total += 3; } else { total += 4; i++; } } } else if (charset === 'utf-16' || charset === 'utf16') { for (var _i = 0, _len = str.length; _i < _len; _i++) { charCode = str.codePointAt(_i); if (charCode <= 0xffff) { total += 2; } else { total += 4; _i++; } } } else { total = str.replace(/[^\x00-\xff]/g, 'aa').length; } return total; } module.exports = byteLen;