JS中英文截取字符串、JS字符串按照规定截取三行

716 阅读1分钟

判断为中文的方法

1、正则
/[\u4e00-\u9fa5]/g.test(字符) ==> 返回ture即为中文
2、charCodeAt
字符串.charCodeAt(字符串中某一字符的索引) > 255 ==> 返回true即为中文

一、按照指定长度截取字符串-按照字节截取

1.1 从索引0开始截取

/**
 * str:需要截取的字符串
 * lenNum:指定长度
 * 返回值:截取后的字符串(带省略号)
*/
const handleStr = function(str, lenNum) {
  var len = 0,
    newStr = ''
  for (var i=0; i<str.length; i++) {
    if(len < lenNum) {
      if (/[\u4e00-\u9fa5]/g.test(str)) {
        len += 2;
      } else {
        len++;
      }
      newStr += str[i]
    } else if(len == lenNum){
      len++
      newStr += '...'
    }
  }
  return newStr;
}

1.2 从指定字节长度开始截取

/**
 * 按照字节截取
 * @param str 需要截取的字符串
 * @param startLength 开始截取的字节长度
 * @param byteLength 需要截取的字节长度
 */
function cutForByte(str, startLength, byteLength) {
  let resultStr = '',
    n = 0

  for (let i=0; i<str.length; i++) {
    if(n >= startLength) {
      if(byteLength == undefined || (byteLength != undefined && n <= startLength + byteLength)) {
        resultStr += str.substr(i, 1)
      }
    }

    n += str.charCodeAt(i) > 255 ? 2 : 1
  }

  return resultStr
}

二、字节总长度

function byteCount(str) {
  let n = 0
  for (let i = 0; i < str.length; i++) {
    n += str.charCodeAt(i) > 255 ? 2 : 1
  }
  return n
}

三、截取三行

例如:第一行显示8个字节、第二行显示10个字节、第三行显示8个字节,显示不下加省略号

该实例中调用的byteCount()和cutForByte()方法在上面的实例里

const handleStrForGraph = function (str) {
  let firstLineSize = arguments[1] || 8,
    secondLineSize = arguments[2] || 10,
    thirdLineSize = arguments[3] || 8,
    resultStr = ''
    
  str = str.trim()
    
  if(byteCount(str) <= secondLineSize) {
    // 一行
    resultStr = str
  } else if(byteCount(str) > firstLineSize && byteCount(str) <= firstLineSize + secondLineSize) {
    // 两行
    resultStr = cutForByte(str, 0, firstLineSize - 1) + '\n' + cutForByte(str, firstLineSize)
  } else if(byteCount(str) > firstLineSize + secondLineSize && byteCount(str) <= firstLineSize + secondLineSize + thirdLineSize){
    // 三行
    resultStr = cutForByte(str, 0, firstLineSize - 1) + '\n' + cutForByte(str, firstLineSize, secondLineSize - 1) + '\n' + cutForByte(str, secondLineSize)
  } else {
    // 三行以上
    resultStr = cutForByte(str, 0, firstLineSize - 1) + '\n' + cutForByte(str, firstLineSize, secondLineSize - 1) + '\n' + cutForByte(str, firstLineSize + secondLineSize, thirdLineSize - 1 - 2) + '...'
  }

  return resultStr
}