70

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

Danny Fox
  • 35,333
  • 28
  • 67
  • 92
  • 2
    A string does not *have* a length in bytes. This depends on the encoding used. – usr Mar 25 '12 at 22:38

4 Answers4

147

Here is an example:

str = 'äáöü';

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

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

Buffer.byteLength(string, [encoding])

noraj
  • 2,818
  • 1
  • 24
  • 34
stewe
  • 40,424
  • 13
  • 77
  • 74
10
function getBytes(string){
  return Buffer.byteLength(string, 'utf8')
}
Anthony
  • 12,124
  • 13
  • 54
  • 68
2

Alternatively, you can use TextEncoder

new TextEncoder().encode(str).length

Related question

Assume it's slower though

sad comrade
  • 1,052
  • 17
  • 19
0

If you want to specific encoded, here is iconv example

  var iconv = require('iconv-lite');
  var buf =iconv.encode('äáöü', 'utf8');
  console.log(buf.length);
  // output: 8