How to Get the Length of a String in Bytes in JavaScript ?
Last Updated :
24 Jun, 2024
In JavaScript, determining the length of a string in characters is straightforward using the length
property. However, in many cases, particularly when dealing with file sizes, network protocols, or database storage, you might need to know the length of a string in bytes. This is because characters can be represented using different numbers of bytes, depending on the encoding. This article explores various methods to calculate the byte length of a string in JavaScript.
Why Byte Length Matters
The byte length of a string is important in scenarios where storage, transmission, and encoding constraints are critical, such as:
- Network Data Transmission: Ensuring data packets are within size limits.
- File Storage: Calculating file sizes accurately.
- Database Storage: Managing data that may be stored in binary formats or with specific encoding requirements.
- Data Serialization: Ensuring efficient data representation for APIs or protocols.
Understanding Encodings
Before diving into the methods for calculating byte length, it's essential to understand how text is encoded. The most common encodings are:
- UTF-8: Variable-length encoding that uses 1 to 4 bytes per character.
- UTF-16: Uses 2 or 4 bytes per character.
- ASCII: Uses 1 byte per character (limited to 128 characters).
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.
Using Blob API
The Blob
interface creates a binary large object from the string and returns its byte size. It’s useful for handling file-like data in web browsers. This approach is straightforward and works well with browser-based JavaScript.
JavaScript
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("????"))
Output:
13
4
5
5
5
4
Using Buffer
in Node.js
The Buffer
class in Node.js calculates the byte length of a string based on the specified encoding. It’s highly suitable for server-side applications, offering flexibility for various encodings. This method is accurate and efficient for Node.js environments.
JavaScript
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("????"))
Output:
13
4
5
5
5
4
Using the TextEncoder
API
The TextEncoder
API provides an efficient way to encode a string into a specific format (e.g., UTF-8) and retrieve its byte length.
JavaScript
function getByteLength(str) {
const encoder = new TextEncoder();
const byteArray = encoder.encode(str);
return byteArray.length;
}
// Example usage:
const str = 'Hello, ?!';
console.log(getByteLength(str));
Similar Reads
JavaScript - How To Get The Last Caracter of a String? Here are the various approaches to get the last character of a String using JavaScript.1. Using charAt() Method (Most Common)The charAt() method retrieves the character at a specified index in a string. To get the last character, you pass the index str.length - 1.JavaScriptconst s = "JavaScript"; co
3 min read
JavaScript - How to Pad a String to Get the Determined Length? Here are different ways to pad a stirng to get the specified length in JavaScript.1. Using padStart() MethodThe padStart() method can be used to pad a string with the specified characters to the specified length. It takes two parameters, the target length, and the string to be replaced with. If a nu
3 min read
How to Find the Length of an Array in JavaScript ? JavaScript provides us with several approaches to count the elements within an array. The length of an array lets the developer know whether an element is present in an array or not which helps to manipulate or iterate through each element of the array to perform some operation. Table of Content Usi
3 min read
How to Get the Size of an Array in JavaScript To get the size (or length) of an array in JavaScript, we can use array.length property. The size of array refers to the number of elements present in that array. Syntaxconst a = [ 10, 20, 30, 40, 50 ] let s = a.length; // s => 5 The JavaScript Array Length returns an unsigned integer value that
2 min read
How to get the size of a JavaScript object ? In this article, we will see the methods to find the size of a JavaScript object. These are the following ways to solve the problem: Table of Content Using Object.keys() methodUsing Object.objsize() methodUsing Object.entries() methodUsing Object.values() methodUsing Object.keys() methodWe can get t
2 min read
JavaScript - How to Find the First and Last Character of a String? Here are the various methods to find the first and last character of a string in JavaScript.1. Using charAt() MethodThe charAt() method retrieves the character at a specified index.JavaScriptconst s = "JavaScript"; const first = s.charAt(0); const last = s.charAt(s.length - 1); console.log(first); c
2 min read
How to Find the Length of JavaScript Dictionary ? In JavaScript, you may often find a dictionary referred to as an object. Therefore, unlike arrays which have a length property, objects (dictionaries) do not have a built-in length property. However, the âlength" of a given dictionary in JavaScript may be determined through counting the pairs of key
3 min read
How To Split a String Into Segments Of n Characters in JavaScript? When working with JavaScript, you might encounter a situation where you need to break a string into smaller segments of equal lengths. This could be useful when formatting a serial number, creating chunks of data for processing, or splitting a long string into manageable pieces. In this article, we
6 min read
JavaScript Convert bytes to human-readable string Given the size of a file (in Bytes), the task is to convert it into human-readable form using JavaScript. Here are a few methods to discuss. Example 1: This example converts the file Size(in Bytes) into human-readable form. It shows the values in decimal and for less than 1024 Bytes, it remains in B
2 min read
Check if a Given String is Binary String or Not in JavaScript Binary strings are sequences of characters containing only the digits 0 and 1. Other than that no number can be considered as Binary Number. We are going to check whether the given string is Binary or not by checking it's every character present in the string.Example:Input: "101010"Output: True, bin
3 min read