My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Get byte size of a given string

Get byte size of a given string

Rajnish Katharotiya's photo
Rajnish Katharotiya
·Jun 17, 2020

Photo by Alizée Baudez on Unsplash

Before going further, I would like to welcome you to a new episode of series call Javascript Useful Snippets. In this series, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat. So, if you haven't read my previous episodes' articles please check it out here or else stay tuned till the end to learn something new 😋 .

Function to get byte size of string : byteSize()

As we all know a byte is one the unit of digital information, and while development taking care of the size of variables, records and files are a much important task. To do that we have various ways but with these functions, it's very easy to do. byteSize() snippet will take a string as an input and in the output, it'll return byte size of a given string. Let's look at the syntax...

const byteSize = str => new Blob([str]).size;

Here, in return, we are using Blob web API to get out byte size. Where Blobs allow you to construct file-like objects and here we are passing our string in array to create one, from that we are returning just size which will be byte size. Let's see some results in a better understanding...

Result One:

const result = byteSize("Hello World")   // output: 11

Result Two:

const result = byteSize("😃")   // output: 4

As we see both results, with plain strings it's returning the same number as a length while in case of emoji it's 4 sizes of bytes. ( For knowledge - The size of the UTF encoding simply defines the minimum number of bytes to be used to represent a character. However, certain characters, like the emoji you are using, require more than 2 bytes to be represented.)

This snippet helped me get byteSize to validate string size. so, I thought to share it with you guys too. I hope you liked my explanation (if yes, hit like ❤️ button ) and if you found it informative then do follow from here because I'll learn and share every day.😋