1 /**2 * Chinese and English string interception3 * @param str to intercept the string4 * @param len to intercept the length5 * @param hasdot whether to add ' ... ' at the end of the string6 * @returns {string}7 *8 */9 Ten functionmysubstring (str, len, Hasdot) { One varNewlength = 0; A varNewstr = ""; - varChineseregex =/[^\x00-\xff]/G; - varSinglechar = ""; the varStrlength = str.replace (Chineseregex, "* *"). length; - for(vari = 0;i < strlength;i++) { -Singlechar =Str.charat (i). toString (); - if(Singlechar.match (chineseregex)! =NULL) { +Newlength + = 2; -}Else { +newlength++; A } at if(Newlength >Len) { - Break; - } -Newstr + =Singlechar; - } - if(Hasdot && strlength >Len) { inNewstr + = "..."; - } to returnNewstr; +}
For example, if you need to keep a maximum of 24 characters (Chinese count two, English is one)
$ (' #inupt '). On (' KeyUp ',function(){ varNewValue = $ ( This). Val (); varTextLength = 0; varsubStr; for(vari = 0; i < newvalue.length; i++) { if(Newvalue.charat (i). Match (/[\u0391-\uffe5]/) ) {TextLength+ = 2; } Else{textLength++; } }; if(textlength>24) {subStr= Mysubstring (newvalue,24); $( This). Val (SUBSTR); }})
Javascript in English string interception