This article describes how to get the length of the mixed string in Chinese and English under JavaScript, here is a good tutorial, interested friends can refer to the following
A colleague posted a post on the company's OA, describing how to get the length of the mixed string in the JavaScript language. is using regular expressions. Code as follows: var str = "Tank is Tank"; var len = str.match (/[^-~]/g) = = null? Str.length:str.length + str.match (/[^-~]/g). length; I checked the book.: Latin Common character set by Space "" (0x20) to "~" (0 x7e), the Chinese character will fall outside the character set, while the regular expression [^-~] represents a character set except for spaces to "~". Code as follows: the String.match (regex) returns the substring of a string in strings that matches the regex of the regular expression in the form of an array, so, Str.match (/[^-~]/g) Returns a Chinese character as an array. For example var str = "Brother DD"; //Show "big, elder brother", the array returns two characters, the array length is 2 alert (Str.match (/[^-~]/g)); So, var len = s Tr.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, can be detected before submitting. NOTE: Some symbols of the above code problems, after the amendment, to the following function. 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; }