【问题标题】:JS: Add ellipsis if string length exceeded 50 charactersJS:如果字符串长度超过 50 个字符,则添加省略号
【发布时间】:2021-05-19 05:10:19
【问题描述】:

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

我试过这样,但它不起作用。

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

有什么建议吗?

【问题讨论】:

  • 你不是说它是怎么不工作的,但我猜你需要括号:... + (post.title.length > 50 ? ... : ...)
  • 但您可能会考虑为此使用 CSS,而不是 JavaScript。见text-overflow: ellipsis。您可能还需要white-space: nowrap

标签: javascript reactjs conditional-operator


【解决方案1】:

也许你可以这样做:

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

【讨论】:

  • 拼写错误。标题->标题:p
  • @Skyler - 感谢您的关注(:已修复
【解决方案2】:

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

{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 唯一的三元运算符,但未来可能会有其他运算符。它的名字是条件操作符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多