Simple Example of js intercepting fixed-length Chinese and English characters

Source: Internet
Author: User

Although js provides a function for calculating the number of bytes occupied by strings, it cannot correctly calculate the number of bytes occupied by Chinese characters, such as document. form1.username. value = "I am a Chinese", document. form1.username. value. length returns 5 instead of 10, which causes some trouble during programming, such as limiting the input of fixed-length characters and intercepting fixed-length strings, the following is a simple function written by myself. It is used to intercept fixed-length strings and is applicable to both Chinese and English. if anything is wrong, please correct it!
Copy codeThe Code is as follows:
// Js intercepts strings and can be used in both Chinese and English
// If the given string is greater than the specified length, return the string with the specified length. Otherwise, return the source string.
Function cutstr (str, len)
{
Var str_length = 0;
Var str_len = 0;
Str_cut = new String ();
Str_len = str. length;
For (var I = 0; I <str_len; I ++)
{
A = str. charAt (I );
Str_length ++;
If (escape (a). length> 4)
{
// The length of the Chinese character must be greater than 4 After encoding
Str_length ++;
}
Str_cut = str_cut.concat ();
If (str_length> = len)
{
Str_cut = str_cut.concat ("...");
Return str_cut;
}
}
// If the given string is smaller than the specified length, the source string is returned;
If (str_length <len ){
Return str;
}
}

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.