我有一堆生成的标题文本,它们都有不同的 .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 做到这一点
任何形式的帮助或任何关于如何实现这一目标的提示都值得赞赏。