javascript-如何在nodejs中获取以字节为单位的字符串长度?

如何在nodejs中获取以字节为单位的字符串长度? 如果我有一个字符串,例如:äáöü,则str.length将返回4。但是如何获得该字符串,形成多少字节呢?

提前致谢

Danny Fox asked 2020-02-22T15:27:26Z
2个解决方案
103 votes

这是一个例子:

str = 'äáöü';

console.log(str + ": " + str.length + " characters, " +
  Buffer.byteLength(str, 'utf8') + " bytes");

// äáöü: 4 characters, 8 bytes

Buffer.byteLength(string,[encoding])

stewe answered 2020-02-22T15:27:46Z
10 votes
function getBytes(string){
  return Buffer.byteLength(string, 'utf8')
}
Antoine answered 2020-02-22T15:28:02Z
translate from https://stackoverflow.com:/questions/9864662/how-to-get-the-string-length-in-bytes-in-nodejs