ata
发布于 2022-08-24 / 31 阅读
0
0

JavaScript 裁剪文本,针对英文单词优化

应该有比我这个更好的办法。

function getShortenedText(text, length = 15) {
    // 将字符串视为数组,当前处理到的字数
    let count = 0;
    // 实际上在数组中的下标
    let realIndex = 0;
    let tempText = text;
    while (tempText.length) {
        // 本次循环要处理的临时字符串
        let tempStr = '';
        // 如果已经到了设定的最大字数,退出循环
        if (count > length) break;
        // 如果字符串中包含字母/数字,则裁掉一整个单词/数
        if (/ ?[a-zA-Z0-9]/.test(tempText[0]))
            tempStr = tempText.match(/ ?[a-zA-Z0-9]+ ?/)[0];
        // 否则只裁掉当前字符串的第一位
        else tempStr = tempText[0];
        count++;
        realIndex += tempStr.length;
        tempText = tempText.slice(tempStr.length);
    }
    text = text.slice(0, realIndex);
    // 如果达到了最大字数,在字符串结尾加省略号
    if (count > length) text += '...';
    return text;
}

评论