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