【问题标题】:How do I find all the words (complete words) up to the 65 character in a string?如何在字符串中找到最多 65 个字符的所有单词(完整单词)?
【发布时间】:2020-05-22 00:13:06
【问题描述】:

我正在尝试针对 Google SEO 优化我的标题(html 中的标题标签)。

我有 3-4 行长的产品标题,看起来像垃圾。我想基本上找到一个字符串中 65 个字符之前的最后一个完整单词。

因此,如果“foo bar baz buzz”是一个长字符串的中间,“baz”中的“a”是第 65 个字符,我只想排除“baz”及其后面的所有内容。

【问题讨论】:

标签: javascript string pattern-matching


【解决方案1】:

这就是我最终的结果:

function truncateTitle(str, len = 60) {
  //get a temporal substring with the desired length
  if (str.length <= len) {
    return str;
  }

  const temp = str.substr(0, len);

  //get the last space index
  const lastSpaceIdx = temp.lastIndexOf(' ');

  //get the final substring
  return temp.substr(0, lastSpaceIdx).trim();
}

【讨论】:

    【解决方案2】:

    嗯!我喜欢其他解决方案,但我想自己尝试一下。

    我意识到如果最后一个单词是完整的,那么它后面必须有一个空格

    所以你需要做的就是将你想要的长度增加+1。如果第 66 个字符是空格,那么它之前的最后一个单词是完整的,您不需要丢弃它。如果不是,则丢弃。

    如果最后一个字符是一个空格,那么无论何时你在空格处.split()它都会创建一个空字符串作为最后一个元素,因为它将最后一个空格解释为一个分割点 - 所以你可以安全地.pop() 最后一个元素,知道它要么不完整要么为空。

    示例 sn-p

    // generates really long string with the entire alphabet
    var str = new Array(100).fill('abcdefghijklmnopqrstuvwxyz').join(' ');
    
    // defines the last char you want to consider
    var len = 65;
    
    // splits the string at that length + 1
    var words = str.slice(0, len + 1).split(/\s+/);
    
    // discards last element, which is either empty or incomplete
    words.pop();
    
    // only full alphabets will be displayed
    console.log(words);

    【讨论】:

      【解决方案3】:

      您应该检查字符串是否比所需长度长,如果是...

      var title = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In id diam vitae enim maximus consequat sit amet eu elit. Sed.";
      
      const substr_length = 65;
      
      //get a temporal substring with the desired length
      var temp = title.substr(0, substr_length);
      
      //get the last space index
      var ls_index = temp.lastIndexOf(" ");
      
      //get the final substring
      var short_title = temp.substr(0, ls_index).trim();
      
      //done
      

      【讨论】:

      • 美观、简单、直观。
      • 其实我稍微修改了一下。你可以使用lastIndexOf(' ');
      • 你是对的。我用那个改变修改了我的答案。
      猜你喜欢
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 2012-07-07
      相关资源
      最近更新 更多