admin管理员组文章数量:1135618
How to get the string length in bytes in nodejs? If I have a string, like this: äáöü
then str.length will return with 4. But how to get that, how many bytes form the string?
How to get the string length in bytes in nodejs? If I have a string, like this: äáöü
then str.length will return with 4. But how to get that, how many bytes form the string?
- 3 A string does not have a length in bytes. This depends on the encoding used. – usr Commented Mar 25, 2012 at 22:38
6 Answers
Reset to default 163Here is an example:
str = 'äáöü';
console.log(str + ": " + str.length + " characters, " +
Buffer.byteLength(str, 'utf8') + " bytes");
// äáöü: 4 characters, 8 bytes
Buffer.byteLength(string, [encoding])
function getBytes(string){
return Buffer.byteLength(string, 'utf8')
}
Alternatively, you can use TextEncoder
new TextEncoder().encode(str).length
Related question
Assume it's slower though
console.log(Buffer.from('example..').length)
This depends where the string is.
In JavaScript engines (at least, in most of them, including V8, used by Node.js and Chromium/Chrome), strings are encoded as UTF-16 internally. In UTF-16 encoding, every character is either 2 or 4 bytes long. Every character that's common in any major human language (and many that aren't) are encoded in 2 bytes (one code unit), while characters from rarer languages, emoji, and unusual symbols are often encoded in 4 bytes (two code units).
Moreover, the JavaScript string
本文标签:
javascriptHow to get the string length in bytes in nodejsStack Overflow
版权声明:本文标题:javascript - How to get the string length in bytes in nodejs? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人,
转载请联系作者并注明出处:http://www.betaflare.com/web/1736935747a1956940.html,
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
length
property actually does not return the number of characters in the string, it returns the number of code units. For example, '
发表评论