Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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("Geeksforgeeks"))
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("Geeksforgeeks"))
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

My Personal Notes arrow_drop_up
Last Updated : 01 Apr, 2021
Like Article
Save Article
Similar Reads
Related Tutorials