javascript - 如何在 jQuery 中 chop 字符串?

标签 javascript jquery string

我的标题很长,想 chop 它们,但要以不打断单词的方式,我的意思是剪切发生在单词之间,而不是剪切一个单词。

如何使用 jquery 做到这一点?

最佳答案

来自: jQuery text truncation (read more style)

试试这个:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";

您还可以使用插件:

作为字符串的扩展

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};

用作

"This is your title".trimToLength(10);

关于javascript - 如何在 jQuery 中 chop 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11806995/

相关文章:

javascript - Selenium-Webdriver,driver.manage().window().getRect()返回错误值?

javascript - 代码无法使用数字数组创建 BST

jquery - CSS - 根据背景更改文本颜色

jquery - 从 JSON 中获取键名

jquery - 日期选择器不显示在框架上

string - 在 Julia 中搜索字符串并返回条件输出的最佳方法?

javascript - ECharts-如何显示带有 3 行图例的水平滚动条,如果项目不适合 3 行则滚动

javascript - 如何正确制作此动画?

c - 基数树实现中的无限循环问题

python - 使用 f 字符串舍入 float