Get all Substrings of a String

To generate all possible substrings of a given string, you can use nested loops to iterate through all possible start and end positions. Here’s an example in JavaScript:

Generate all substrings iteratively

  const getSubstrings = (string) => {
    const substrings = [];

    for (let i = 0; i < string.length; i++) {
      for (let j = i + 1; j <= string.length; j++) {
        substrings.push(string.slice(i, j));
      }
    }
    return substrings;
  }

  const inputString = "abcd";
  const result = getSubstrings(inputString);
  console.log(result); 
  // ["a", "ab", "abc", "abcd", "b", "bc", "bcd", "c", "cd", "d"]

Generate all substrings recursively

  const getSubstrings = (str) => {
    const result = [];
    const recurse = (startIndex, endIndex) => {
      if (endIndex === str.length) {
        return;
      }
      
      if (startIndex > endIndex) {
        recurse(0, endIndex + 1);
      } else {
        result.push(str.slice(startIndex, endIndex + 1));
        recurse(startIndex + 1, endIndex);
      }
    }

    recurse(0, 0);
    return result;
  }

  const inputString = "abcd";
  const output = getSubstrings(inputString);
  console.log(output);