JS gets the string byte number method. Share to everyone for your reference. Specific as follows:
As you know, getting the length of a string can be obtained by
So what's the number of bytes to get this string?
The English letter must be the same as the lenght and the number of bytes: 1
While Chinese lenght=1, bytes = 2
So what needs to be done is to calculate the number of bytes in the Chinese characters.
Method One:
Alert (' A '. Replace (/[^\u0000-\u00ff]/g, "AAA"). length); Principle: Replace Chinese characters with 2 English letters, then the number of bytes is changed to 3 English letters in the 2,//example. So the number of bytes popped is 3, if you want to correct, of course, is replaced by 2 letters//\u0000 This is the Unicode encoding
Method Two:
var str= ' me me '; 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 the 6//principle is also very simple, with regular judgment is not Chinese, if so, the number of bytes added 1.
Regular expressions that match Chinese characters: [\U4E00-\U9FA5]
Match double-byte characters (including kanji): [^\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)//Unicode encoding of the character that gets the num position of the string
fromCharCode (num)//Get the Unicode encoding corresponding to the character
JS Get string Byte number method summary