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;
}