Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the string length in bytes in nodejs?

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?

Thanks in advance

like image 601
Danny Fox Avatar asked Mar 25 '12 22:03

Danny Fox


People also ask

How do you find the length of a string in a byte?

So a string size is 18 + (2 * number of characters) bytes. (In reality, another 2 bytes is sometimes used for packing to ensure 32-bit alignment, but I'll ignore that). 2 bytes is needed for each character, since . NET strings are UTF-16.

How many bytes is a string JavaScript?

The size of a JavaScript string is. Always 2 bytes per character.


1 Answers

Here is an example:

str = 'äáöü';  console.log(str + ": " + str.length + " characters, " +   Buffer.byteLength(str, 'utf8') + " bytes");  // äáöü: 4 characters, 8 bytes 

Buffer.byteLength(string, [encoding])

like image 119
stewe Avatar answered Sep 20 '22 08:09

stewe