How to get the length of the string as bytes in Nodejs?
Published September 24, 2020
To get the string length in bytes in Node.js, you can use the
byteLength() method in the
Let's say you have a string called
// string const str = "Hello World!";
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
- The method accepts types of
String, etc as the first argument.
- The second argument is the encoding, the default is
- The method returns the size of the bytes as an
See this example live in repl.it.