How to get the length of a string in bytes in JavaScript ?
Last Updated :
01 Apr, 2021
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) => {
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...