Determining the Size of a JavaScript String in Bytes
JavaScript strings store characters using UCS-2 encoding, typically occupying two bytes per character. However, the exact byte size can vary depending on the JavaScript implementation, page encoding, and content-type.
To reliably determine the size of a JavaScript string in bytes, consider using the following approach:
<code class="javascript">const string = 'This is a sample string.'; // Create a Blob object from the string const blob = new Blob([string]); // Retrieve the byte size of the Blob const byteSize = blob.size;</code>
In this code, the Blob constructor takes an array containing the string as an argument and creates a binary data object. The .size property of the Blob provides the byte size of the data it contains, including the string.
Here are a few examples to demonstrate the use of this approach:
<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 // Handling 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>
By using this method, you can accurately determine the byte size of a JavaScript string, regardless of the JavaScript implementation, page encoding, or content-type.
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!