2

我有一堆生成的标题文本,它们都有不同的 .Length 但在字符串的特定起始索引处,我想找到最近的空格,然后删除它后面的文本以及空格,然后添加“... ”。

最重要的部分是它不应该延长 49 长度

例子:

"What can UK learn from Spanish high speed rail when its crap"

我想确保它变成:

"What can UK learn from Spanish high speed rail..."

我怎样才能用 Jquery 做到这一点?

我有一个 C# 代码可以实现这一点:

public static string TrimLength(string text, int maxLength)
{
    if (text.Length > maxLength)
    {
        maxLength -= "...".Length;
        maxLength = text.Length < maxLength ? text.Length : maxLength;
        bool isLastSpace = text[maxLength] == ' ';
        string part = text.Substring(0, maxLength);
        if (isLastSpace)
            return part + "...";
        int lastSpaceIndexBeforeMax = part.LastIndexOf(' ');
        if (lastSpaceIndexBeforeMax == -1)
            return part + "...";
        else
            return text.Substring(0, lastSpaceIndexBeforeMax) + "...";
    }
    else
        return text;
}

但我不知道如何用 jquery 做到这一点

任何形式的帮助或任何关于如何实现这一目标的提示都值得赞赏。

4

3 回答 3

4

这是此常见任务的通用 Javascript 解决方案。jQuery 不是必需的,但用于$.trim保持输入字符串整洁。

var ellipsis = "...";

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;
}

并测试:

sentence = "The quick brown fox jumps over a lazy dog.";

for (var i = 10; i <= 50; i += 10){
    console.log(TrimLength(sentence, i));
};

输出:

The...
The quick brown...
The quick brown fox jumps...
The quick brown fox jumps over a...
The quick brown fox jumps over a lazy dog. 

> jsFiddle 演示

还值得注意的是,您可以使用 CSS 实现类似的效果text-overflow,这可能更适合您的情况:http: //jsfiddle.net/LtQ2j/3/

于 2013-05-18T11:08:21.410 回答
2
于 2013-05-18T11:01:18.300 回答
0

为了完整起见,您可以使用 2-arg 形式做得更好lastIndexOf

var ellipsis = "...";

function Truncate(text, maxLength)
{
    if (text.length <= maxLength)
        return text;

    maxLength -= ellipsis.length;
    var space = text.lastIndexOf(" ", maxLength);
    if (space >= 0)
        maxLength = space;

    return text.slice(0, maxLength) + ellipsis;
}
于 2013-05-18T16:10:45.343 回答