我如何确保当我的省略号被添加lastindexof space时,它也会在添加之前检查它的字母表,而不是特殊字符

How can I make sure that when my ellipsis gets added lastindexof space it also checks its alphabet before it gets added and not special chars

本文关键字:添加 检查 特殊字符 字母表 确保 何确保 lastindexof space 省略号 我的      更新时间:2023-09-26

代码如下:

 function TrimLength(text, maxLength) {
        text = $.trim(text);
        if (text.length > maxLength) {
            text = text.substring(0, maxLength - ellipsis.length)
            return text.substring(0, text.lastIndexOf(" ")) + ellipsis;
        }
        else
            return text;
    }

我的问题是它做了以下事情:

hello world and an...
The curse of the gaming backlog –...

我想确保它是这样做的:

hello world and...
The curse of the gaming backlog...

我想我需要确保有像(a,b,c,d等)这样的字母字符,没有特殊字符。

任何形式的帮助都是感激的

你可以这样开始:

function cutoff(str, maxLen) {
    // no need to cut off
    if(str.length <= maxLen) {
        return str;
    }
    // find the cutoff point
    var oldPos = pos = 0;
    while(pos!==-1 && pos <= maxLen) {
        oldPos = pos;
        pos = str.indexOf(" ",pos) + 1;
    }
    if (pos>maxLen) { pos = oldPos; }
    // return cut off string with ellipsis
    return str.substring(0,pos) + "...";
}

,它至少给了你基于单词而不是字母的截止值。如果你需要额外的过滤,你可以添加它,但这将给你一个像"游戏积压的诅咒-…"这样的截断,这看起来并没有错,老实说。