This article mainly introduces five methods for determining the string length in JS and distinguishes Chinese and English. For more information, see
Objective: To calculate the String length (1 character in English and 2 Characters in Chinese) Method 1: the code is as follows: String. prototype. gblen = function () {var len = 0; for (var I = 0; I <this. length; I ++) {if (this. charCodeAt (I)> 127 | this. charCodeAt (I) = 94) {len + = 2;} else {len ++;} return len;} Method 2: the code is as follows: function strlen (str) {var len = 0; for (var I = 0; I <str. length; I ++) {var c = str. charCodeAt (I); // Add 1 if (c> = 0x0001 & c <= 0x007e) to a single byte | (0xff60 <= c & c <= 0xff9f) {Len ++;} else {len + = 2 ;}} return len ;}method 3: Code: var jmz ={}; jmz. getLength = function (str) {// <summary> obtain the actual length of the string, which is 2 in Chinese, english 1 </summary> // <param name = "str"> string to be obtained </param> var realLength = 0, len = str. length, charCode =-1; for (var I = 0; I <len; I ++) {charCode = str. charCodeAt (I); if (charCode> = 0 & charCode <= 128) realLength + = 1; else realLength + = 2;} return realLength ;}; Method 4: Code Var l = str. length; var blen = 0; for (I = 0; I <l; I ++) {if (str. charCodeAt (I) & 0xff00 )! = 0) {blen ++;} Method 5: Replace the dual-byte with two single-byte values and obtain the Length Code as follows: getBLen = function (str) {if (str = null) return 0; if (typeof str! = "String") {str + = "";} return str. replace (/[^ \ x00-\ xff]/g, "01"). length ;}