JS:如果字符串长度超过 50 个字符,则添加省略号

JS: Add ellipsis if string length exceeded 50 characters

如果字符串超过 50 个字符,是否可以使用三元运算符添加“...”?

我这样试过,但是不行。

{post.title.substring(0, 50) + post.title.length > 50
                    ? '...'
                    : ''}

有什么建议吗?

条件运算符¹ 相当贪婪。要让它仅应用于 + 之后的表达式部分,您需要括号(分组运算符):

{post.title.substring(0, 50) + (post.title.length > 50
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−^
                    ? '...'
                    : '')
// −−−−−−−−−−−−−−−−−−−−−^
}

但是您可以考虑为此使用 CSS,而不是 JavaScript。参见 text-overflow: ellipsis。您可能还需要 white-space: nowrapoverflow: hidden;

.limit {
    max-width: 20em;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}
<div>With limit:</div>
<div class="limit">Now is the time for all good men to come to the aid of their country</div>
<div>Without limit:</div>
<div>Now is the time for all good men to come to the aid of their country</div>


¹ ? :a 三元运算符(接受三个操作数的运算符),目前它是 JavaScript 唯一的三元运算符,但是将来可能还有其他人。它的名字是条件运算符。

也许你可以这样做:

var shortTitle = post.title.length > 50 ? post.title.substring(0,50) + "..." : post.title;