DEV Community

Cover image for How to get the length of the string as bytes in Nodejs?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to get the length of the string as bytes in Nodejs?

Originally posted here!

To get the string length in bytes in Node.js, you can use the byteLength() method in the Buffer class.

Let's say you have a string called Hello World!,

// string
const str = "Hello World!";
Enter fullscreen mode Exit fullscreen mode

Now let's use the Buffer.byteLength() to get the bytes of the string.

// string
const str = "Hello World!";

// get string length in bytes
const bytes = Buffer.byteLength(str, "utf-8");

console.log(bytes); // 12
Enter fullscreen mode Exit fullscreen mode
  • The method accepts types of Buffer, String, etc as the first argument.
  • The second argument is the encoding, the default is utf-8.
  • The method returns the size of the bytes as an integer.

See this example live in repl.it.

Feel free to share if you found this useful 😃.


Top comments (0)