This article is an example of how JS gets the number of string bytes. Share to everyone for your reference. Specifically as follows:
As you all know, getting the length of a string can be obtained by using length.
So what is the number of bytes to get this string?
The English alphabet must be lenght the same as the number of bytes: 1
In Chinese lenght=1, the number of bytes = 2
So what you need to do is figure out the number of bytes in the Chinese character.
Method One:
1 2 3 4 5 |
Alert (' A '. Replace (/[^u0000-u00ff]/g, "AAA"). length); Principle: Replace the Chinese characters with 2 English letters, then the number of bytes is 2,//The example is replaced with 3 English letters. So the number of bytes ejected is 3, if you want to be correct, of course, it's replaced with 2 letters.//u0000 This represents a Unicode encoding |
Method Two:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16-17 |
var str= ' I-i-I '; var Bytescount; for (var i = 0; i < str.length; i++) {var c = Str.charat (i); if (/^[u0000-u00ff]$/.test (c))//Match Double-byte {bytescount = 1; else {bytescount = 2;}} alert (Bytescount); The result is 6//principle is also very simple, with the regular judge is not Chinese, if it is, the number of bytes plus 1. |
Matching regular expressions for Chinese characters: [U4E00-U9FA5]
Match Double-byte characters (including Chinese characters): [^X0000-X00FF]
can be used to calculate the length of a string (a double-byte character length meter 2,ascii character 1)
Several functions in JS:
CharAt (num)//Gets the character of the num position of the string
charCodeAt (num)/To get the Unicode encoding of the character of the string's num position
fromCharCode (num)/Get the character for the Unicode encoding
I hope this article will help you with your JavaScript programming.