Js intercepts a simple example of fixed length Chinese and English characters

  • 2020-03-29 23:59:00
  • OfStack

Js while provides the calculating function of the string of bytes, but not the number of bytes of correct calculation of Chinese characters, such as document. Form1. Username. Value = "I am a Chinese," the document. The form1. Username. Value. The length is returned 5 instead of 10, then give some trouble when programming, such as restrictions on fixed length of the input character, intercept fixed length of string is because of this problem can not meet the desired effect, the following is write a simple function, Used for intercepting fixed length strings, both in Chinese and English.

//Js intercepts strings in both Chinese and English
//If the given string is greater than the specified length, intercepting the specified length returns, or returns 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 Chinese characters is greater than 4 after encoding
         str_length++;
         }
         str_cut = str_cut.concat(a);
         if(str_length>=len)
         {
         str_cut = str_cut.concat("...");
         return str_cut;
         }
    }
    //Returns the source string if the given string is less than the specified length.
    if(str_length<len){
     return  str;
    }
}

Related articles: