Computer >> Computer tutorials >  >> Programming >> Javascript

Get all substrings of a string in JavaScript recursively


We are required to write a JavaScript function that takes in a string as the only argument. The function should recursively construct all possible substrings of the input string.

Then the function should return an array containing all the substrings.

Example

const str = 'example';
const buildSubstrings = (str = '') => {
   let i, j;
   const res = [];
   for (i = 0; i < str.length; i++) {
      for (j = i + 1; j < str.length + 1; j++) {
         res.push(str.slice(i, j));
      };
   };
   return res;
};
console.log(buildSubstrings(str));

Output

And the output in the console will be −

[
   'e', 'ex', 'exa',
   'exam', 'examp', 'exampl',
   'example', 'x', 'xa',
   'xam', 'xamp', 'xampl',
   'xample', 'a', 'am',
   'amp', 'ampl', 'ample',
   'm', 'mp', 'mpl', 'mple',
   'p', 'pl', 'ple',
   'l', 'le', 'e'
]