user4184969
user4184969

Reputation:

How to get all combinations of word in string

I want to get all neighboring combinations of words in string like string get all combinations and I want to get

get all combinations
all combinations
get all
all
get
combinations

and I write next code

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;
    }
}

can I improve or simplify this task (get all neighboring combinations of words ) p.s. sorry for my English

Upvotes: 4

Views: 2270

Answers (1)

dyachenko
dyachenko

Reputation: 1212

hello maybe this help you

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

Upvotes: 11

Related Questions