Javascript Substring Algorithm

i need to make a function /method given a string it will substring it to as many sets as the length of the string.
EG
"hi" —> h,i, hi
"bye" —> b,y,e,by,ye, bye
"home" —> h,o,m,e,ho, om,me, hom, ome, home
"kirupa" —>
k, i, r,u, p, a, ki, ir, ru, up, pa, kir, iru, rup, upa, kiru, irup, rupa, kirup, irupa

Thank you

Can you post some of the solutions you’ve tried? I can think of a few recursive approaches that would work! :slight_smile:

Every time i ask a question, i sit back n figure it out. lol
i simply asked myself what do i specifically need help with n BOOM i got it.

function subword(word){
var ans=word; //save original word
var spltW=‘’; //deletes first char of word
var len= word.length;
var arr=;
var i=0;

while (i < len) {

for (var j=1; j<len; j++){
spltW= word.slice(0,j);
arr.push(spltW);
}
word= word.slice(1);
i++;
}
arr.push(ans);

//remove duplicate

var narr=[arr[0]];

for (var i=0; i<arr.length; i++){
if(narr.indexOf(arr[i])==-1){narr.push(arr[i]);}
}
jarr= narr;

//order
var marr=;
for (var i=0; i<jarr.length; i++){
for (var j=0; j<jarr.length; j++){
if(jarr[j].length == i+1){marr.push(jarr[j]);}
}
}
console.log(marr);
}

1 Like