user2085143 user2085143 - 1 year ago 88
Javascript Question

Get all substrings of a string in 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 = [];


function getAllSubstrings(str) {

var start = 1;

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

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




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.

Answer Source

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';
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download