从字面上理解您的问题,如果您只想显示 75 个字符,那么您可以简单地按照@MohammadAdil 的建议进行操作。但是,您最终会得到 79 个字符(74 + 3 (...) + 两个空格。只需通过拉出 72 个字符并附加"..."
. 来限制它。当然,如果您实际上需要限制为 75 个可见字符,或者如果您只是指帖子的 75 个字符,然后添加省略号。
我个人的建议是把它留给一个可以为你做的图书馆(或者如果可以的话,使用一个)。Underscore是一个相当小的库,其中包含大量方便的实用程序,它可以确定您是否可以内置与它们的实现(例如_.each
使用Array#forEach
是否已定义)。话虽这么说,underscore.string是下划线的一个插件,它包含许多有用的字符串操作函数,比如_.toSentence
它会接受和数组一样["one", "two", "three"]
并返回"one, two and three"
,但更重要的是你得到truncate
and prune
。
truncate
并且prune
仅在字符串处于其限制时才执行截断,例如,根据他们的示例:
// Assume the underscore.string functions have bene mixed into _
_.truncate("Hello, World", 5) // "Hello..."
_.truncate("Hello", 10) // "Hello"
该truncate
函数将剪切文本中间句子,这prune
是一个更干净的替代方案,因为它在最接近指定长度的分词处剪切文本。根据他们的例子:
_.prune("Hello, cruel world", 15) // "Hello, cruel..."
// for comparison
_.truncate("Hello, cruel world", 15) // "Hello, cruel wo..."