Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the length of a string in bytes in JavaScript?
In JavaScript, getting the length of a string in bytes is different from getting its character count. A byte is a unit of data that is 8 binary bits long, and while most ASCII characters use 1 byte, Unicode characters like emojis or special symbols may use multiple bytes.
Here are examples of strings and their byte lengths:
Examples:
- "JavaScript" ? 10 bytes (each ASCII character = 1 byte)
- "20?" ? 5 bytes (? symbol uses 3 bytes in UTF-8)
- "Tutorials Point" ? 15 bytes
There are two main approaches to calculate string byte length in JavaScript:
Using the Blob API (Browser)
The Blob API creates file-like objects and can calculate the byte size of a string. This method works in all modern browsers.
Syntax
const getByteLength = (str) => {
return new Blob([str]).size;
}
Example
<!DOCTYPE html>
<html>
<head>
<title>String Byte Length - Blob API</title>
</head>
<body>
<h2>String Byte Length Using Blob API</h2>
<div id="output"></div>
<script>
const getByteLength = (str) => {
return new Blob([str]).size;
}
const strings = ["JavaScript", "20?", "Hello ?", "Tutorials Point"];
const output = document.getElementById('output');
strings.forEach(str => {
const bytes = getByteLength(str);
output.innerHTML += `"${str}" = ${bytes} bytes<br>`;
});
</script>
</body>
</html>
"JavaScript" = 10 bytes "20?" = 5 bytes "Hello ?" = 9 bytes "Tutorials Point" = 15 bytes
Using Buffer API (Node.js)
The Buffer API is available only in Node.js environments. It creates a buffer object that represents the string in bytes and provides the length property.
Example
const getByteLength = (str) => {
return Buffer.from(str, 'utf8').length;
}
console.log(`"JavaScript" = ${getByteLength("JavaScript")} bytes`);
console.log(`"20?" = ${getByteLength("20?")} bytes`);
console.log(`"Hello ?" = ${getByteLength("Hello ?")} bytes`);
console.log(`"Tutorials Point" = ${getByteLength("Tutorials Point")} bytes`);
"JavaScript" = 10 bytes "20?" = 5 bytes "Hello ?" = 9 bytes "Tutorials Point" = 15 bytes
Comparison
| Method | Environment | Encoding | Performance |
|---|---|---|---|
| Blob API | Browser only | UTF-8 | Good |
| Buffer API | Node.js only | Configurable (UTF-8 default) | Excellent |
Key Points
- ASCII characters (a-z, 0-9) use 1 byte each
- Unicode characters like ? use 2-4 bytes in UTF-8 encoding
- Emojis typically use 4 bytes each
- String.length returns character count, not byte count
Conclusion
Use the Blob API for browser environments and Buffer API for Node.js to accurately calculate string byte length. Both methods handle Unicode characters correctly, unlike the basic string length property.
