javascript - 仅在评论中显示链接的一小部分

标签 javascript ruby-on-rails ruby-on-rails-4

如果用户在评论中插入了链接,则该链接需要被 chop 为 20 个字符。

如何制作?

例如:

Lorem ipsum: https://github.com/plataformatec/devise 

结果应该是这样。

Lorem ipsum: https://github.com/plataforma...

最佳答案

你想从哪一端 chop ?

使用String#[]您可以从任意一端获取子字符串:

s = "string with more than twenty characters"
s[0, 20] # get the first 20 characters
=> "string with more tha"
s[s.size-20, s.size] # the last 20 characters
=> "an twenty characters"

Rails 还添加了 truncate字符串方法:

"string with more than twenty characters".truncate(20)
=> "string with more ..."
"string with more than twenty characters".truncate(20, omission: "")
=> "string with more tha"

希望有帮助。

关于javascript - 仅在评论中显示链接的一小部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21611591/

相关文章:

javascript - IE7 中的开发者工具查看控制台日志消息

ruby-on-rails - 通过回形针从 URL 保存图像

ruby-on-rails - Rails 模型方法 : which is preferable?

ruby-on-rails-4 - 在 Rails 4.2 中,如何将整数转换为枚举?

javascript - ReactJS 中的 "Legacy octal literals are not allowed in strict mode"是什么意思?

javascript - 如何创建类似 Google Closure 的继承结构

javascript - 如何创建一个具有多维数组输入、转换它并输出新的多维数组的函数

ruby-on-rails - Omniauth-facebook 与设计 : "Missing passthru" errors

mysql - 嵌套模型的新建和创建操作不保存 user_id

sql - 获取错误 "function week(timestamp without time zone) does not exist"