Wednesday, June 10, 2026
HomeLanguagesJavascriptHow to get the length of a string in bytes in JavaScript...

How to get the length of a string in bytes in JavaScript ?

Task: To find the size of the given string in bytes.

Example:

Input: "GeeksForGeeks"
Output: 13 bytes

Input: 20€
Output: 5 bytes

Input: "????"
Output: 4 bytes

To achieve this we have two ways the first one is using the Blob API and the second is Buffer API, the first one works with the browser, and the second works with the Node.js environment. blob object is simply a group of bytes that holds the data stored in a file. To read the bytes of a string using blog we create a new instance of Blob object then we pass the string inside it and by using the size property we can get the bytes of a string.

Example 1: Using Blob API.

Javascript




<script>
const len = (str) => {
  
  // Creating new Blob object and passing string into it 
  // inside square brackets and then 
  // by using size property storin the size 
  // inside the size variable
  let size = new Blob([str]).size;
  return size;
  
console.log(len("Geeksforneveropen"))
console.log(len("true"))
console.log(len("false"))
console.log(len("12345"))
console.log(len("20€"))
console.log(len("????"))
</script>


Output:

13
4
5
5
5
4

Example 2: Using Buffer API. Now there is another way to achieve this in NodeJS using Buffer. So first create the Buffer object and then pass the string inside it and using the length property you can get the size of the string

Javascript




<script>
const len = (str) => {
  let size = Buffer.from(str).length;
  return size;
  
console.log(len("Geeksforneveropen"))
console.log(len("true"))
console.log(len("false"))
console.log(len("12345"))
console.log(len("20€"))
console.log(len("????"))
</script>


Output:

13
4
5
5
5
4
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6896 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS