Get all substrings of a string in JavaScript

You need two nested loop for the sub strings.

function getAllSubstrings(str) {
  var i, j, result = [];

  for (i = 0; i < str.length; i++) {
      for (j = i + 1; j < str.length + 1; j++) {
          result.push(str.slice(i, j));
      }
  }
  return result;
}

var theString = 'somerandomword';
console.log(getAllSubstrings(theString));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Below is a recursive solution to the problem

let result = [];

function subsetsOfString(str, curr = '', index = 0) {
  if (index == str.length) {
    result.push(curr);
    return result;
  }
  subsetsOfString(str, curr, index + 1);
  subsetsOfString(str, curr + str[index], index + 1);
}

subsetsOfString("somerandomword");
console.log(result);

A modified version of Accepted Answer. In order to give the minimum string length for permutation

function getAllSubstrings(str, size) {
  var i, j, result = [];
  size = (size || 0);
  for (i = 0; i < str.length; i++) {
    for (j = str.length; j - i >= size; j--) {
      result.push(str.slice(i, j));
    }
  }
  return result;
}

var theString = 'somerandomword';
console.log(getAllSubstrings(theString, 6));

Tags:

Javascript