格式化文案,首尾固定长度显示,中间隐藏

313 阅读1分钟
/**
 * 格式化文案,首尾固定长度显示,中间隐藏
 * @param textContent
 * @param startLength
 * @param endLength
 * @param EllipsisStyle 省略位置需要替换成的字符串,比如省略部分替换成***或者...
 * @param suffixString 以传入内容分割需要格式化的字符串,从最后开始招一个为准
 * @returns
 */
export const middleEllipsis = (
  textContent: string | number,
  startLength: number,
  endLength: number,
  ellipsisStyle: string,
  suffixString?: string,
) => {
  textContent = String(textContent);
  let textContentArr = [];
  let suffix = '';

  if (suffixString) {
    (textContentArr as string[]) = textContent.split(suffixString);
    suffix = suffixString + textContentArr[textContentArr.length - 1];
    textContent = textContent.replace(`${suffix}`, '');
  }

  if (startLength + endLength >= textContent.length) {
    if (suffixString) {
      return `${textContent}${suffix}`;
    }
    return textContent;
  } else {
    if (suffixString) {
      return `${textContent.slice(0, startLength)}${ellipsisStyle}${textContent.slice(-endLength,)}${suffix}`;
    }
    return `${textContent.slice(0, startLength)}${ellipsisStyle}${textContent.slice(-endLength)}`;
  }
};

export const fileNameEllipsis = (fileName) => middleEllipsis(fileName, 7, 7, '...', '.');

export const phoneEllipsis = (fileName) => middleEllipsis(fileName, 3, 4, '***');

export const emailEllipsis = (fileName) => middleEllipsis(fileName, 1, 1, '***', '@');

export const folderNameEllipsis = (fileName) => middleEllipsis(fileName, 7, 7, '...');