Some colleagues posted a post on the company's OA to introduce how to get the length of the Chinese -English mixed string in JavaScript.
The regular expression is used.
Copy code code as follows:
Var Str = "The tank is the transliteration of Tank";
var len = str.match (/[^ -]/g) == null? Str.Length: str.Length + Str.match (/[^ -]/g) .Length;
I checked the book and understood a bit:
The commonly used characters in Western text consist of the space "(0x20) to" ~ "(0x7e). Essence
Copy code code as follows:
String.match (reGex) will return a string of regular expression regex in the form of a string in the form of an array, so
Str.match (/[^ -~]/g) will return Chinese characters in the form of an array. For example
var str = "DD Brother";
// Show "Big, Brother", return two Chinese characters in the array, and the array length is 2
alert (str.match (/[^ -]/g);
In this way, var len = str.match (/[^ -]/g) == NULL? Str.Length: Str.Length + Str.Match (/[^ -]/g). LENGTH; The correct length is.
In JavaScript, the length of a Chinese character is also calculated as 1. It is often errors that cause excessive length in the database. Now this method can be detected before submitting.
Note: There are some problems with the above code. After the correction, it is changed to the following functions.
Copy code code as follows:
Function get_strlenth (str)
{{
var len = 0;
if (Str.Match (/[^ -]/G) == NULL)
{{
len = str.Length;
}
else
{{
len = str.length + str.match (/[^ -]/g) .length;
}
Return len;
}