Javascript in English string interception

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.