Javascript/jQuery 从字符串中获取前 100 个字符,尊重完整的单词

Javascript/jQuery Get first 100 characters from string, respecting full words

我遇到了很多关于这个的问题,我只找到了 PHP 的解决方案。 jQuery/javascript 此站点上没有解决方案。

我想做的是我想显示前 100 个字符,但我不想删除最后一个字,因为它没有意义。

就像说 this is myself 是最后一个词,所以我们经常取子串,而 y 是第 100 个词,然后它会像 this is my 一样切割它,这意味着更少。所以我想要它 this is..

我的原代码:

jQuery(".block-text .success-inner-content").each(function(){
    if(jQuery(this).text().length > 100){
        jQuery(this).text(jQuery(this).text().substr(0,98)+'..');
    }
});

这里 block-text .success-inner-content class 循环生成包含文本的 Divs 列表。

我自己解决了。该解决方案使用 substr() 和最重要的 lastIndexOf() 函数 javascript 。

jQuery(".block-text .success-inner-content").each(function () {
    if (jQuery(this).text().length > 100) {
        var str =  jQuery(this).text().substr(0,98);
        var wordIndex = str.lastIndexOf(" ");

        jQuery(this).text(str.substr(0, wordIndex) + '..');
    }
});

lastIndexOf 方法采用第二个参数来确定搜索的开始位置,因此您无需在找到最后一个 space:

之前削减字符串
jQuery(".block-text .success-inner-content").each(function () {
  var text = jQuery(this).text();
  if (text.length > 100) {
    jQuery(this).text(text.substr(0, text.lastIndexOf(' ', 97)) + '...');
  }
});

您也可以使用 text 方法代替 each 来循环元素并为每个元素设置文本:

jQuery(".block-text .success-inner-content").text(function (i, text) {
  return text.length > 100 ? text.substr(0, text.lastIndexOf(' ', 97)) + '...' : text;
});

或者你可以用正则表达式来做...像这样 -

var s = 'What I want to do is I want to show first 100 characters but I don't want to cut the last word, as it would be meaningless.';

console.log(s.match(/(.{1,19}\w)\s/)[1]+'...');

这匹配任意 20 个字符,以单词字符结尾,后跟 space。

此致