Home >Web Front-end >JS Tutorial >How to Determine the Size of a JavaScript String in Bytes?
JavaScript String Size in Bytes
Problem:
You have a JavaScript string that occupies approximately 500 KB when transmitted via the server in UTF-8 encoding. How can you determine its size in JavaScript?
Background:
JavaScript employs UCS-2 encoding, typically using two bytes per character. However, potential variations in JavaScript implementation or page/content-type encoding raise questions about whether this is a constant relationship.
Answer:
To obtain the string's size in bytes, leverage the Blob constructor as follows:
<code class="javascript">console.info( new Blob(['?']).size, // 4 new Blob(['?']).size, // 4 new Blob(['??']).size, // 8 new Blob(['??']).size, // 8 new Blob(['I\'m a string']).size, // 12 // Correction for strings with lone characters in the surrogate pair range: new Blob([String.fromCharCode(55555)]).size, // 3 new Blob([String.fromCharCode(55555, 57000)]).size // 4 (not 6) );</code>
Explanation:
The Blob object allows you to represent binary data and retrieve its size in bytes. By passing your string within an array to the Blob constructor, you can obtain its actual size, regardless of potential variations in character encoding or implementation.
The above is the detailed content of How to Determine the Size of a JavaScript String in Bytes?. For more information, please follow other related articles on the PHP Chinese website!