我正在尝试编写一个仅返回句子前八个单词的函数。但是,如果第一句话少于八个单词,我只想返回第一句话-而不是前八个单词。
例如,如果测试的句子是“这是一个比八个单词长得多的句子,但是仅输出前八个单词。”
输出为:“这是一个更长的句子”
如果我添加了标点符号(该函数正在查找)以将输入更改为“这是一个句子。该词比八个单词长得多,但是仅输出前八个单词。”
输出为:“这是一个句子。”
代码如下:
#>
#> $`weight/individual %.% kg[2]`
答案 0 :(得分:2)
在处理句子定界符之前,您似乎将字符串拆分成单词数组,这似乎使您感到困惑。只需先处理句子定界符,然后就可以使用slice将单词数限制为最多8个。
仅使用split
,slice
和join
的紧凑版本:
const longer = 'This is a sentence that is much longer than eight words, but only the first eight words will be outputted.';
const shorter = 'This is a sentence. that is much longer than eight words, but only the first eight words will be outputted.';
const trunc = (s) => {
return s.split(/[.?!]/)[0].split(' ').slice(0, 8).join(' ');
}
console.log(trunc(longer));
// This is a sentence that is much longer
console.log(trunc(shorter));
// This is a sentence
如果您需要保留8个单词或更少的句子的结尾标点符号,则可以在组合中添加search
:
const longer = 'This is a sentence that is much longer than eight words, but only the first eight words will be outputted.';
const shorter = 'This is a sentence. that is much longer than eight words, but only the first eight words will be outputted.';
const trunc = (s) => {
let i = s.search(/[.?!]/) + 1;
return s.slice(0, i ? i : s.length).split(' ').slice(0, 8).join(' ');
}
console.log(trunc(longer));
// This is a sentence that is much longer
console.log(trunc(shorter));
// This is a sentence.
答案 1 :(得分:0)
const checkString = str => str.substr(0, /[.?!]/.exec(str).index + 1).split(' ').filter((_, idx) => idx < 8).join(' ');
console.log(checkString("This is a sentence that is much longer than eight words, but only the first eight words will be outputted."));
console.log(checkString("This is a sentence. This is another sentence."));
console.log(checkString("This is a sentence? This is another sentence."));
console.log(checkString("This is a sentence! This is another sentence."));