JS 获取字符串长度,截取字符串

截取中英文字符串,一个汉字相当于2个字符,多余部分用...补全,比如要保留3个字:
'你好'=>'你好'
'你好啊啊'=>'你好啊...'
'你好aaa'=>'你好aa...'
'你hao啊'=>'你hao...' 等等

代码如下:

cutStr = (str, len) => {
  let charLength = 0;
  for (let i = 0; i < str.length; i++) {
    charLength += encodeURI(str.charAt(i)).length > 2 ? 1 : 0.5;
    if (charLength >= len) {
      const subLen = charLength === len ? i + 1 : i;
      return `${str.substr(0, subLen)}...`;
    }
  }
  return str;
}

升级版(常用):

比如元素宽度可以放下4个中文字符,那么当str长度为4时,则不省略,代码如下:

getLength = (str) => {
  let charLength = 0;
  for (let i = 0; i < str.length; i++){
    charLength += encodeURI(str.charAt(i)).length > 2 ? 1 : 0.5;
  }
  return charLength;
}
cutStr = (str, len) => {
  if(getLength(str)>len+1) {
    let charLength = 0;
    for (let i = 0; i < str.length; i++) {
      charLength += encodeURI(str.charAt(i)).length > 2 ? 1 : 0.5;
      if (charLength >= len) {
        const subLen = charLength === len ? i + 1 : i;
        return `${str.substr(0, subLen)}...`;
      }
    }
  }
  return str;
}
posted @ 2020-12-16 17:58  ZerlinM  阅读(824)  评论(0编辑  收藏  举报