一个用来输出每行指定数量字符,指定行数,指定换行符的函数

开发时遇到一种情况,一段字符串:

  • 每行指定多少字符
  • 最多n行
  • 多余部分用省略号代替

这种需求遇到过挺多次了(如echarts的自定义formatter、v-html绑定的文本等),每次解决方法都不一样,其实还是很有共性的,觉得可以写一个方法用来处理这个字符串。

下面是这个方法的代码,防止以后用到,因此记录在此:

/**
 * txt - 需要格式化的文本
 * maxLine - 要多少行执行省略
 * lineCount - 每行要放多少个字符
 * breakWord - 换行符(\n或者<br />)
 */
function textEllipsis(txt, maxLine, lineCount, breakWord = "\n") {
    
    
  const CHPat = /[\u4e00-\u9fa5]/; // 中文字的正则
  const CHPunctuation =
    /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;

  const splitWords = txt.split("");
  let copyWords = txt.split("");

  let addedBreak = 0; // 已经添加的换行符的数量,用来添加换行符
  let currentLineCount = 0; // 当前行字符的统计

  for (let i = 0; i < splitWords.length; i++) {
    
    
    let w = splitWords[i];
    const isCH = CHPat.test(w) || CHPunctuation.test(w);
    if (isCH) {
    
    
      currentLineCount += 2;
    } else {
    
    
      currentLineCount += 1;
    }

    // 已到指定行数的最后字符
    if (addedBreak === maxLine - 1 && currentLineCount >= lineCount * 2 - 3) {
    
    
      copyWords.splice(i + addedBreak);
      copyWords.push(". . .");
      break;
    }

    // 当前行已经超过指定长度
    if (
      currentLineCount >= lineCount * 2 - 1 ||
      currentLineCount >= lineCount * 2
    ) {
    
    
      copyWords.splice(i + addedBreak + 1, 0, breakWord);
      addedBreak += 1;
      currentLineCount = 0;
    }
  }
  return copyWords.join("");
}

主要有四个传参,分别是:

  • txt - 需要格式化的字符串
  • maxLine - 需要格式化成多少行
  • lineCount - 每一行要有多少个中文字符(两个英文字符 = 一个中文字符)
  • breakWord - 换行符。默认\n,也可以传<br />这种

猜你喜欢

转载自blog.csdn.net/vet_then_what/article/details/127802066
今日推荐