How to get the string length in bytes in nodejs?


Question

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

1
46
3/25/2012 10:28:49 PM

Accepted Answer

Here is an example:

str = 'äáöü';

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

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

Buffer.byteLength(string, [encoding])

101
3/25/2012 10:59:01 PM

function getBytes(string){
  return Buffer.byteLength(string, 'utf8')
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon