js irregular string for byte interception

Encountered a small problem, the string includes "Chinese characters", "numbers", "English", "symbols" and other uncertain content, but when displaying, it needs to be intercepted and displayed after being too long. Simple string interception may not be able to To meet the needs, I found a method to calculate the number of bytes based on the string, and then perform byte interception.

Pasting the code directly may not be very comprehensive, but it is also a new way of thinking, just record it and paste the code directly

    // 计算字节并截取
    filterStr(str) {
      let realLength = 0;
      const len = str.length;
      let charCode = -1;
      for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) realLength += 1;
        else realLength += 2;
        if (realLength > 30) { // 超过30个字节进行省略号展示
          return str.substring(0, i) + '...';
        }
      }
      return str;
    },

Guess you like

Origin blog.csdn.net/jinse29/article/details/130718220