我正在尝试优化我的标题为谷歌搜索引擎优化(标题标签在html)。
我有3-4行长的产品标题,只是看起来像垃圾。我想基本上找到弹簧中65个字符之前的最后一个完整的单词。
因此,如果'foo bar baz buzz‘是一个长字符串的中间,"baz“中的"a”是65个字符,我只想排除"baz“及其后面的所有字符。
发布于 2020-05-22 09:08:44
嗯!我喜欢其他的解决方案,但我想给它自己的机会。
我意识到的是,如果最后一个单词是完整的,那么在它后面必须有一个空格。
所以你需要做的就是把你想要的长度增加+1。如果第66个字符是空格,那么它之前的最后一个单词就是完整的,您不需要丢弃它。如果不是,则丢弃。
如果最后一个字符是一个空格,那么每当你在空格上执行.split()时,它都会创建一个空字符串作为最后一个元素的,因为它将最后一个空格解释为一个拆分点-所以你可以安全地.pop()最后一个元素,因为你知道它要么是不完整的,要么是空的。
示例代码片段
// 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);
发布于 2020-05-22 14:35:55
这就是我最终想要的:
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();
}发布于 2020-05-22 08:49:24
您应该检查字符串是否比所需的长度长,如果是...
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();
//donehttps://stackoverflow.com/questions/61945802
复制相似问题