Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all substrings of a string in JavaScript

Tags:

javascript

I have the following function to get all of the substrings from a string in JavaScript. I know it's not correct but I feel like I am going about it the right way. Any advice would be great.

 var theString     = 'somerandomword',
     allSubstrings = []; 

getAllSubstrings(theString);

function getAllSubstrings(str) {

  var start = 1;

  for ( var i = 0; i < str.length; i++  ) {

     allSubstrings.push( str.substring(start,i) ); 

  }

} 

console.log(allSubstrings)

Edit: Apologies if my question is unclear. By substring I mean all combinations of letters from the string (do not have to be actual words) So if the string was 'abc' you could have [a, ab, abc, b, ba, bac etc...] Thank you for all the responses.

like image 272
user2085143 Avatar asked Nov 26 '16 13:11

user2085143


3 Answers

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; }
like image 92
Nina Scholz Avatar answered Nov 11 '22 05:11

Nina Scholz


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));
like image 20
vineetv2821993 Avatar answered Nov 11 '22 06:11

vineetv2821993


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);
like image 1
Paras Wadhwa Avatar answered Nov 11 '22 06:11

Paras Wadhwa