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:01
Original
667 people have browsed it

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

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!

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!