Realization of Js automatically intercepting string length and adding ellipsis of …

  • 2021-07-26 06:33:29
  • OfStack

JavaScript string processing function, according to the defined length of the string, cut off the excess part of the append..., many times the content displayed on the web page needs to be reduced to "..." This method is used to deal with the fixed length of string display, and the ultra-long part is replaced by "...":


/** Parameter description:  

 *  According to the length of interception first use string, extra-long part append …  

 * str  Object string  

 * len  Target byte length  

 *  Return value:   Processing the result string  

 */ 

 function cutString(str, len) { 

   //length The length of Chinese characters read by attribute is 1 

   if(str.length*2 <= len) { 

     return str; 

   } 

   var strlen = 0; 

   var s = ""; 

   for(var i = 0;i < str.length; i++) { 

     s = s + str.charAt(i); 

     if (str.charCodeAt(i) > 128) { 

       strlen = strlen + 2; 

       if(strlen >= len){ 

         return s.substring(0,s.length-1) + "..."; 

       } 

     } else { 

       strlen = strlen + 1; 

       if(strlen >= len){ 

         return s.substring(0,s.length-2) + "..."; 

       } 

     } 

   } 

   return s; 

 } 


Related articles: