如何获取字符串中单词的所有组合

How to get all combinations of word in string

本文关键字:单词 组合 字符串 何获取 获取      更新时间:2023-09-26

我想获得字符串中所有相邻的单词组合字符串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;
    }
}

我能改进或简化这个任务吗(获取所有相邻的单词组合)p.s.对不起我的英语

你好,也许这能帮助你

    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(' ') + ', ');
      }
    }