A colleague posted a post on the company's OA, introducing how to get the length of a mixed Chinese and English string in JavaScript.
uses regular expressions.
var str = "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 got it a little bit:
The commonly used Western character set consists of spaces " " (0x20) to "~" (0x7e). Chinese characters will fall outside this character set. The regular expression [^ -~] represents the character set except spaces to "~".
string.match(regex) will return characters in the form of an array The string matches the substring of the regular expression regex. Therefore,
str.match(/[^ -~]/g) will return Chinese characters one by one in the form of an array. For example
var str = "dd brother";
//Display "big brother", return two Chinese characters in the array, 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 ;You can get the correct length of str.
In JavaScript, the length of a Chinese character is also calculated as 1, which often causes an error of exceeding the standard length when submitted to the database. Now with this method, you can check it before submitting.
Note: Some symbols in the above code have problems. After correction, they were changed to the following functions.
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;
}