Categories
JavaScript Answers

How to Get a JavaScript String’s Length in Bytes?

Spread the love

We can use the Blob constructor to get the size of a string in bytes.

For instance, we can write:

const {
  size
} = new Blob(["hello"]);
console.log(size)

We create a blob from a string with the Blob constructor.

Then we get the size property of the blob to get the size.

We should see that size is 5 from the console log.

Get a JavaScript String’s Length in Bytes with TextEncoder

We can also use the TextEncoder constructor to get the size of a string in bytes.

For example, we can write:

const size = (new TextEncoder().encode('hello')).length
console.log(size)

We create a new TextEncoder instance and call encode on it with the string we want to get the size from.

And we should get the same result as the previous example.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *