JS Get string Byte number method summary

Source: Internet
Author: User

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.

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.