SoFunction
Updated on 2025-02-28

js method to obtain string byte count

This article example describes the method of obtaining the number of bytes of string bytes by JS. Share it for your reference. The details are as follows:

As we all know, we can get the length of a string by length.
So what about getting the number of bytes of this string?

The English letters must be the same as length and bytes: both are 1
And Chinese length=1, byte number=2
Therefore, what is needed is to calculate the number of bytes of Chinese characters.

Method 1:

alert('a'.replace(/[^\u0000-\u00ff]/g,"aaa").length); 
//Principle: Replace Chinese characters with 2 English letters, then the number of bytes is 2.//In the example, it was replaced with 3 English letters.//Then the pop-up number of bytes is 3. If it is to be correct, of course it will be replaced with 2 letters.//\u0000This meansunicodecoding

Method 2:

var str='I I I';
var bytesCount;
for (var i = 0; i < ; i++)
{
  var c = (i);
  if (/^[\u0000-\u00ff]$/.test(c)) //Match double bytes  {
  bytesCount += 1;
  }
  else
  {
  bytesCount += 2;
  }
}
alert(bytesCount);
//The result is 6//The principle is also very simple,Use regularity to determine whether it is Chinese,If so,Add bytes1。

Regular expression matching Chinese characters: [\u4e00-\u9fa5]

Match double-byte characters (including Chinese characters): [^\x0000-\x00ff]

Can be used to calculate the length of a string (one double-byte character length meter 2, ASCII character meter 1)

Several functions in JS:

charAt(num) //Get the character at the num position of the string
charCodeAt(num)//Get unicode encoding of characters at num position of string
fromCharCode(num)//Get the characters corresponding to the unicode encoding

I hope this article will be helpful to everyone's JavaScript programming.