JS Get string Byte number method summary

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.