/* * param str to intercept the string * param L to intercept the byte length, note that the byte is not a character, a kanji two bytes * Return truncated string */function cutstr (str,l) { var result = ' ', strlen = str.length,//String length Chrlen = str.replace (/[^\x00-\xff]/g, ' * * * '). length;//byte Lengths if (chrlen<= L) {return str;} for (Var i=0,j=0;i<strlen;i++) { var chr = Str.charat (i); if (/[\x00-\xff]/.test (CHR)) { J + +;//ASCII code is 0-255, one character is a byte length }else{ j+=2;//ASCII code is 0-255, A character is a length of two bytes } if (j<=l) {///after adding the current character, if the total byte length is less than or equal to L, the current character will be true + + at result + + chr; } else{//vice versa indicates that result is the nearest L value without splitting the character and returns the return result directly;}} Use Case alert (CUTSTR ("Test 1 string haha", "ten"); Alert (Cutstr ("ABCDEFGHIGKLMN", 10));
JS intercepts character lengths by byte instance 2