JavaScript function code intercepted by a Chinese String

Source: Internet
Author: User

To solve this problem, I wrote a function that intercepts strings based on the number of bytes yesterday.
It is easy to use, just like String. subString (start, end. For example, var str = "cailove"; var str1 = str. subCHStr (2, 2); var str2 = str. subCHString (2, 4); alert (str1 + "=" + str2 );

Copy codeThe Code is as follows:
Code
// Calculate the string length
String. prototype. strLen = function (){
Var len = 0;
For (var I = 0; I <this. length; I ++ ){
If (this. charCodeAt (I)> 255 | this. charCodeAt (I) <0) len + = 2; else len ++;
}
Return len;
}
// Split the string into characters and coexist in the array
String. prototype. strToChars = function (){
Var chars = new Array ();
For (var I = 0; I <this. length; I ++ ){
Chars [I] = [this. substr (I, 1), this. isCHS (I)];
}
String. prototype. charsArray = chars;
Return chars;
}
// Determine whether a character is a Chinese character
String. prototype. isCHS = function (I ){
If (this. charCodeAt (I)> 255 || this. charCodeAt (I) <0)
Return true;
Else
Return false;
}
// Truncate the string (from the start byte to the end byte)
String. prototype. subCHString = function (start, end ){
Var len = 0;
Var str = "";
This. strToChars ();
For (var I = 0; I <this. length; I ++ ){
If (this. charsArray [I] [1])
Len + = 2;
Else
Len ++;
If (end <len)
Return str;
Else if (start <len)
Str + = this. charsArray [I] [0];
}
Return str;
}
// Truncate the string (The length byte is truncated from the start byte)
String. prototype. subCHStr = function (start, length ){
Return this. subCHString (start, start + length );
}

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.