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

2 javascript

我想得到字符串中所有相邻的单词组合,如字符串get all combinations ,我想得到

get all combinations
all combinations
get all
all
get
combinations
Run Code Online (Sandbox Code Playgroud)

我写下一个代码

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以改进或简化这项任务(得到所有相邻的单词组合)对不起我的英语

dya*_*nko 6

你好,也许这对你有帮助

    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(' ') + ', ');
      }
    }
Run Code Online (Sandbox Code Playgroud)