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?

Share Improve this question edited Dec 29, 2022 at 3:30 starball 49.3k28 gold badges195 silver badges865 bronze badges asked Mar 25, 2012 at 22:28 Danny FoxDanny Fox 40.7k29 gold badges71 silver badges96 bronze badges 1
  • 3 A string does not have a length in bytes. This depends on the encoding used. – usr Commented Mar 25, 2012 at 22:38
Add a comment  | 

6 Answers 6

Reset to default 163

Here 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 length property actually does not return the number of characters in the string, it returns the number of code units. For example, '

本文标签: javascriptHow to get the string length in bytes in nodejsStack Overflow