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


Solution 1:

Here is an example:

str = 'äáöü';

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

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

Buffer.byteLength(string, [encoding])

Solution 2:

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

Solution 3:

Alternatively, you can use TextEncoder

new TextEncoder().encode(str).length

Related question

Assume it's slower though