How to get the string length in bytes in nodejs?

Javascriptnode.js

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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

Solution 3 - Javascript

Alternatively, you can use TextEncoder

new TextEncoder().encode(str).length

Related question

Assume it's slower though

Solution 4 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanny FoxView Question on Stackoverflow
Solution 1 - JavascriptsteweView Answer on Stackoverflow
Solution 2 - JavascriptAnthonyView Answer on Stackoverflow
Solution 3 - Javascriptsad comradeView Answer on Stackoverflow
Solution 4 - Javascript陳庭勛View Answer on Stackoverflow