import { getTextDisplayLen } from "./getTextDisplayLen" /** * 截断文本,省略号在中间 * @param options.enableDisplayLen 是否考虑中文长度 * @example * truncateString("1234567890", 5) // "1...0" */ export function truncateString( text: string, len: number, options?: { enableDisplayLen?: boolean } ) { let testLen = options?.enableDisplayLen ? getTextDisplayLen(text) : text.length if (testLen <= len) { return text } // 分隔符长度 ... let separatorLen = 3 let lmitLen = len - separatorLen let halfLen = lmitLen / 2 let start = text.substring(0, Math.ceil(halfLen)) let end = text.substring(testLen - Math.floor(halfLen)) return `${start}...${end}` } /** * 截断文本,省略号在开头 * @param options.enableDisplayLen 是否考虑中文长度 * @example * truncateStringStart("1234567890", 5) // "...90" */ export function truncateStringStart( text: string, len: number, options?: { enableDisplayLen?: boolean } ) { let testLen = options?.enableDisplayLen ? getTextDisplayLen(text) : text.length if (testLen <= len) { return text } // 分隔符长度 ... let separatorLen = 3 let lmitLen = len - separatorLen let end = text.substring(testLen - lmitLen) return `...${end}` } /** * 截断文本,省略号在结尾 * @param options.enableDisplayLen 是否考虑中文长度 * @example * truncateStringEnd("1234567890", 5) // "12..." */ export function truncateStringEnd( text: string, len: number, options?: { enableDisplayLen?: boolean } ) { let testLen = options?.enableDisplayLen ? getTextDisplayLen(text) : text.length if (testLen <= len) { return text } // 分隔符长度 ... let separatorLen = 3 let lmitLen = len - separatorLen let start = text.substring(0, lmitLen) return `${start}...` }