Analysis of JS Implementation of Friendly Interception with Chinese String

  • 2021-08-03 08:52:25
  • OfStack

In this paper, an example is given to describe the friendly interception function of JS containing Chinese strings. Share it for your reference, as follows:

When displaying strings, avoiding strings that are too long often intercepts strings. Usually, substr or substring methods of js and length attributes of strings are used

Handling non-Chinese strings is straightforward, but the length attribute value of Chinese characters is 1 instead of 2, so the handling is not very friendly.

For example, you have a string 1234567890 and 123456789 zero.

You only want to display a 5-bit length, which is often done as str = str. substr (0, 5);

But the width of 12345 is different from that of 12345, because Chinese often takes 2 bytes. In order to display better,

So encapsulate the js below, and he will recognize that the length of Chinese characters is 2


$.String.Substr = function (str, n) {// String interception   Including Chinese processing 
  if (str.replace(/[\u4e00-\u9fa5]/g, "**").length <= n) {
    return str;
  }
  else {
    var len = 0;
    var tmpStr = "";
    for (var i = 0; i < str.length; i++) {// Traversing string 
      if (/[\u4e00-\u9fa5]/.test(str[i])) {// Chinese   The length is two bytes 
        len += 2;
      }
      else {
        len += 1;
      }
      if (len > n) {
        break;
      }
      else {
        tmpStr += str[i];
      }
    }
    return tmpStr + " ...";
  }
};

PS: Here, we recommend two online character statistics tools, all of which include the calculation functions of Chinese, English and symbols. I believe they have a certain reference value for everyone:

Online word count tool:
http://tools.ofstack.com/code/zishutongji

Online Character Statistics and Editing Tools:
http://tools.ofstack.com/code/char_tongji

More readers interested in JavaScript can check the topics of this site: "Summary of JavaScript Mathematical Operation Usage", "Summary of json Operation Skills in JavaScript", "Summary of JavaScript Switching Special Effects and Skills", "Summary of JavaScript Search Algorithm Skills", "Summary of JavaScript Animation Special Effects and Skills", "Summary of JavaScript Error and Debugging Skills", "Summary of JavaScript Data Structure and Algorithm Skills" and "Summary of JavaScript Traversal Algorithm and Skills"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: