JS prototype string truncation Function

Source: Internet
Author: User

Prototype is an API written in Javascript, including the expansion of JavaScript classes such as string and array. You can embed Javascript files and use them directly. CopyCode The Code is as follows: 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 );
}
VaR li = Document. getelementsbyname ("listtitle ");
For (VAR I = 0; I <li. length; I ++)
{
Li [I]. innerhtml = Li [I]. innerhtml. subchstr (0, 28) + "...";
}

Prototype is used to inherit prototype objects, mainly to save memory space.

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.