JS intercept character length by byte instance 2

Source: Internet
Author: User

/* * 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

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.