Js substr supports Chinese truncation Function Code (Chinese is double byte)

Source: Internet
Author: User

Copy codeThe Code is as follows:
<Script language = "JavaScript">
// Obtain the total number of characters
Function getChars (str ){
Var I = 0;
Var c = 0.0;
Var unicode = 0;
Var len = 0;
If (str = null | str = ""){
Return 0;
}
Len = str. length;
For (I = 0; I <len; I ++ ){
Unicode = str. charCodeAt (I );
If (unicode <127) {// determines whether it is a single character or a dual character
C + = 1;
} Else {// chinese
C + = 2;
}
}
Return c;
}
Function sb_strlen (str ){
Return getChars (str );
}
// Intercept characters
Function sb_substr (str, startp, endp ){
Var I = 0; c = 0; unicode = 0; rstr = '';
Var len = str. length;
Var sblen = sb_strlen (str );
If (startp <0 ){
Startp = sblen + startp;
}
If (endp <1 ){
Endp = sblen + endp; //-(str. charCodeAt (len-1) <127 )? 1: 2 );
}
// Start point
For (I = 0; I <len; I ++ ){
If (c> = startp ){
Break;
}
Var unicode = str. charCodeAt (I );
If (unicode <127 ){
C + = 1;
} Else {
C + = 2;
}
}
// Start to fetch
For (I = I; I <len; I ++ ){
Var unicode = str. charCodeAt (I );
If (unicode <127 ){
C + = 1;
} Else {
C + = 2;
}
Rstr + = str. charAt (I );
If (c> = endp ){
Break;
}
}
Return rstr;
}
// Call example:
Function getaskfilename (filename ){
Short_filename = filename;
If (sb_strlen (short_filename)> 61 ){
Short_filename = sb_substr (short_filename, 0, 36) + '...' + sb_substr (short_filename,-20 );
}
Return short_filename;
}
Var chara = 'ni, hello! '
Js_self = chara. substr (4 );
Test = sb_substr (chara, 4 );
Alert ("js_self:" + js_self + "ext:" + test );
</Script>

Copy codeThe Code is as follows:
Function mb_strlen (str ){
Var len = 0;
For (var I = 0; I <str. length; I ++ ){
Len ++ = str. charCodeAt (I) <0 | str. charCodeAt (I)> 255? (Charset = 'utf-8 '? 3: 2): 1;
}
Return len;
}

<Html> </pead> <body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

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.