Ali Abdulaal
Ali Abdulaal

Reputation: 73

How to generate keywords from string with javascript

I want to generate all possible keywords from string

For example, my string is:

mystring = "IPHONE X FOR SELL";

I checked splice and I got part of what I need

array = mystring.split(" ");
//output [ "IPHONE", "X", "FOR", "SELL" ]

So how can I make output like the bellow array ?

[ IPHONE, X, FOR, SELL, IPHONE X, X FOR, FOR SELL, IPHONE X FOR, X FOR SELL, IPHONE X FOR SELL ]

Upvotes: 0

Views: 620

Answers (1)

Alizadeh118
Alizadeh118

Reputation: 1064

const string = "IPHONE X FOR SELL";

const items = string.split(' ');

const result = [];

for (let i = 0; i < items.length; i++) {

    for (let j = 1; j <= items.length; j++) {

        const slice = items.slice(i,j);

        if (slice.length)
            result.push(slice.join(' '));
    }

}

console.log(result);

Upvotes: 3

Related Questions