js判断字符超长度中间用...替换

需求如果字符大于14个就中间用....

utils.js


/* 部分隐藏处理
** str 需要处理的字符串
** frontLen  保留的前几位
** endLen  保留的后几位
** cha  替换的字符串

*/
export function strReplace(str, frontLen, endLen, cha) {
  const len = str.length - frontLen - endLen
  if (len > 0) {
    let newStr = ''
    for (let i = 0; i < len; i++) {
      newStr = cha
    }
    return (
      str.substring(0, frontLen) + newStr + str.substring(str.length - endLen)
    )
  } else {
    return str
  }
}

页面引用

import { strReplace } from '@/utils/utils.js'
this.fileList = fileList.map(item => {
          const fileExtension = item.name.substring(item.name.lastIndexOf('.'))
          const filename = item.name.substring(0, item.name.lastIndexOf('.'))
          return {
            ...item,
            name: strReplace(filename, 14, 3, '...') + fileExtension
          }
        })

页面效果

猜你喜欢

转载自blog.csdn.net/qq_40190624/article/details/128618090