Home > Web Front-end > JS Tutorial > body text

How to Determine the Size of a JavaScript String in Bytes

Mary-Kate Olsen
Release: 2024-10-19 07:17:30
Original
286 people have browsed it

How to Determine the Size of a JavaScript String in Bytes

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!