How to get the length of Chinese and English mixed strings in JavaScript _javascript tips

Source: Internet
Author: User
Tags array length mixed

A colleague posted a post on the company's OA, describing how to get the length of the mixed string in the JavaScript language.

The regular expression is used.

Copy Code code as follows:

var str = "tank is Tank";
var len = str.match (/[^-~]/g) = = null? Str.length:str.length + str.match (/[^-~]/g). length;

I looked up the book and I got a little bit clear:

The Latin language common character set consists of a space "" (0x20) to "~" (0x7e), and the Chinese character will fall outside the character set, while the regular expression [^-~] represents a character set other than a space to "~".
Copy Code code as follows:

The String.match (regex) returns the substring of the regular expression regex in string strings as an array, so
Str.match (/[^-~]/g) returns a Chinese character as an array. For example
var str = "Brother DD";
Display "big, elder brother", return two characters in array, array length is 2
Alert (Str.match (/[^-~]/g));

So, var len = Str.match (/[^-~]/g) = = null? Str.length:str.length + str.match (/[^-~]/g). length; You can get the correct lengths of Str.

In JavaScript, the length of a Chinese character is also calculated to be 1, often in the submission to the database caused by the error of the length exceeded, now use this method, you can before the submission of a test.

Note: Some symbols of the above code have problems, after amendment, to the following function.
Copy Code code as follows:

function Get_strlength (str)
{
var len = 0;

if (Str.match (/[^-~]/g) = = null)
{
len = str.length;
}
Else
{
Len = str.length + str.match (/[^-~]/g). length;
}

return Len;
}

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.