首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何查找字符串中最多65个字符的所有单词(完整单词)?

如何查找字符串中最多65个字符的所有单词(完整单词)?
EN

Stack Overflow用户
提问于 2020-05-22 08:13:06
回答 3查看 56关注 0票数 1

我正在尝试优化我的标题为谷歌搜索引擎优化(标题标签在html)。

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

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

EN

回答 3

Stack Overflow用户

发布于 2020-05-22 09:08:44

嗯!我喜欢其他的解决方案,但我想给它自己的机会。

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

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

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

示例代码片段

代码语言:javascript
复制
// 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);

票数 0
EN

Stack Overflow用户

发布于 2020-05-22 14:35:55

这就是我最终想要的:

代码语言:javascript
复制
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();
}
票数 0
EN

Stack Overflow用户

发布于 2020-05-22 08:49:24

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

代码语言:javascript
复制
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
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61945802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档