我的JavaScript字符串很长。我试图将它与连续单词的每个x组合分解成一个数组。例如,如果我的数组
var string = 'This is my example string'
我的x等于3,我会得到类似的东西:
['This', 'This is', 'This is my', 'is', 'is my', 'is my example', 'my', 'my example', 'my example string', 'example string', 'string']
就像,每个组合最多三个单词。我以此为指标进行模糊文本匹配。
答案 0 :(得分:3)
您可以使用双for
循环:
function chunks(str, len) {
const arr = str.match(/\S+/g);
const result = [];
for (let i = 0; i < arr.length; i++) {
const end = Math.min(arr.length, i + len);
for (let j = i + 1; j <= end; j++) {
result.push(arr.slice(i, j).join(" "));
}
}
return result;
}
var string = 'This is my example string';
console.log(chunks(string, 3));
更实用的方法是:
function chunks(str, len) {
return str.match(/\S+/g).flatMap((_, i, arr) =>
arr.slice(i, i + len).map((_, j) => arr.slice(i, i+j+1).join(" "))
);
}
var string = 'This is my example string';
console.log(chunks(string, 3));
答案 1 :(得分:2)
您可以缩小数组,并使用Set
来获取不确定值。
var string = 'This is my example string',
result = [... new Set(string.split(' ').reduce((r, s, i, a) =>
r.concat(
s,
a.slice(i, i + 2).join(' '),
a.slice(i, i + 3).join(' ')
),
[]
))];
console.log(result);
答案 2 :(得分:1)
一种纯功能性方法:
// permuteWords :: Number -> String -> [String]
const permuteWords = count => x => {
const words = x.split (' ')
const wordIndexes = [...words.keys ()]
return wordIndexes.flatMap (i => {
const wordIndexes_ = wordIndexes.slice (i, count + i)
return wordIndexes_.map (i_ =>
words.slice (i, i_ + 1).join (' ')
)
})
}
const output = permuteWords (3) ('This is my example string')
console.log (output)
现在,我已经定义permuteBy
来生成表示排列的索引的平面数组,然后使用它们顺序获取每个单词:
// rangeFromZero :: Number -> [Number]
const rangeFromZero = x => [...Array (x).keys ()]
// permuteBy :: Number -> Number -> [Number]
const permuteBy = x => y => {
const ys = rangeFromZero (y)
return ys.flatMap(i =>
ys.slice (i, x + i).flatMap (i_ => ys.slice(i, i_ + 1))
)
}
// permuteWords :: Number -> String -> [String]
const permuteWords = count => x => {
const words = x.split (' ')
return permuteBy (count) (words.length)
.map (i => words[i])
}
const output = permuteWords (3) ('This is my example string')
console.log (output)