我希望得到字符串中所有相邻的单词组合
字符串get all combinations
我想得到
get all combinations
all combinations
get all
all
get
combinations
我写下一个代码
var string = 'get all combinations';
var result = getKeywordsList(string);
document.write(result);
function getKeywordsList(text) {
var wordList = text.split(' ');
var keywordsList = [];
while (wordList.length > 0) {
keywordsList = keywordsList.concat(genKeyWords(wordList));
wordList.shift();
}
return keywordsList;
}
function genKeyWords(wordsList) {
var res = [wordsList.join(' ')];
if (wordsList.length > 1) {
return res.concat(genKeyWords(wordsList.slice(0, -1)));
} else {
return res;
}
}
我可以改进或简化此任务(获取所有相邻的单词组合) 附:抱歉我的英文
答案 0 :(得分:5)
您好,这可能对您有所帮助
var string = 'get all combinations'
var sArray = string.split(' ');
var n = sArray .length;
for (var i = 0; i < n; i++) {
for (var j = 0; j <= i; j++) {
document.write(sArray .slice(j, n - i + j).join(' ') + ', ');
}
}
&#13;