zoukankan      html  css  js  c++  java
  • 根据字节截字符串,仅供工作中参考,如有侵权,联系作者

    /**
     * 处理select文字过长显示省略号
     * @param {*} _class
     * @param {*} _this
     * @param {*} _len1显示字节长度
     */
    export function showEllipsis (_class, _this, _len1) {
      let inputDom = document.querySelectorAll(_class)
      // console.log(inputDom)
      inputDom.forEach(item => {
        _this.$nextTick(() => {
          if (getByteLen(item.value) > _len1) {
            // console.log(reBytesStr(item.value, _len1) + '...')
            item.value = reBytesStr(item.value, _len1) + '...'
          }
        })
      })
    }
    /**
     * 字符串根据字节截取字符串
     * @param {*} str
     * @param {*} len
     */
    export function reBytesStr (str, len) {
      if ((!str && typeof (str) !== 'undefined')) {
        return ''
      }
      let num = 0
      let str1 = str
      let returnStr = ''
      for (let i = 0, lens = str1.length; i < lens; i++) {
        num += ((str1.charCodeAt(i) > 255) ? 2 : 1)
        if (num > len) { // 字节大于规定字节退出循环
          break
        } else {
          returnStr = str1.substring(0, i + 1)
        }
      }
      return returnStr
    }
    /**
     * 判断字符串占用字节
     * @param {*} val
     */
    export function getByteLen (val) {
      let len = 0
      for (let i = 0; i < val.length; i++) {
        if (val[i].match(/[^x00-xff]/ig) !== null) {
          len += 2 // 如果是全角,占用两个字节
        } else {
          len += 1 // 半角占用一个字节
        }
      }
      return len
    }

    备注:举例使用 

    showEllipsis('.el-dialog .el-select input', this, 14)
    小凤凰newObject
  • 相关阅读:
    Redundant Connection
    Recover Binary Search Tree
    Min Stack
    *Flatten Binary Tree to Linked List
    Copy List with Random Pointer
    Binary Tree Maximum Path Sum
    Arithmetic Slices
    Integer to English Words
    Unique Email Addresses
    Mycat(水平拆分--分表 全局序列)
  • 原文地址:https://www.cnblogs.com/xiaofenghuang/p/13841660.html
Copyright © 2011-2022 走看看