How To Get The Number Of Bytes In A String In JavaScript

Getting the number of bytes in a JavaScript string can be very useful.

For example, at the time of this article being written, 01 October 2021, Twitter limits posts to 280 bytes. If you use just Latin characters, numbers, or other ASCII characters in a Twitter post, then the number of characters would be equal to the number of bytes since each ASCII character is made with 1 byte.

But in other languages, or other non-ASCII characters like emojis, the character would likely be made with more than 1 byte.

Essentially there are 2 steps to getting the number of bytes in a string in JavaScript.
1. Convert the string into a Blob object.

2. Get the .size attribute from the previously made Blob object and that will give you the number of bytes in the string.

Below is an example using just ASCII characters.

let example_string_1 = "Hello World"
let example_string_1_as_blob = new Blob([example_string_1])
console.log(example_string_1_num_bytes.size) // should give you 11

You can also confirm that the length of the original string is the same as the number of its bytes.

console.log(example_string_1.length) // you should also get 11

Example Where Number of Bytes in A JavaScript String Is Different From The Length

Now, for an example where the number of bytes is different from the number of characters, and would make a difference in things like a Twitter post. We will use Chinese Characters. Each Chinese character is represented by a 3 byte code.

Let’s have a string that says “How are you?” in Chinese which is 你好嗎.

let example_string_2 = "你好嗎"
let example_string_2_num_bytes = new Blob([example_string_2])
console.log(example_string_2_num_bytes.size) // will give 9 as an output

To confirm that the number of bytes is different from its length:

console.log(example_string_2.length) // you should get 3

If you were to paste in 你好嗎 in a Twitter post, it would count as 9 bytes, not 3, towards the 280 byte limit for a post.

What did you think of this article? Do you have anything to add? Let’s discuss it in the comments below.

Software To Install Every Time With Lubuntu 20.04

Lubuntu 20.04, the latest LTS version of Ubuntu using LXQt, is quite a great operating system. While the default desktop environment for Ubuntu, Gnome, is nice, LXQt is designed to be light and fast. This article will discuss the best software to install every time with Lubuntu 20.04 to give you the best experience using it. Continue reading “Software To Install Every Time With Lubuntu 20.04”