Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all combinations of word in string

Tags:

javascript

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


1 Answers

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(' ') + ', ');
      }
    }
like image 179
dyachenko Avatar answered Oct 23 '25 08:10

dyachenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!