Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  44] [ 1]  / answers: 1 / hits: 32898  / 8 Years ago, sat, november 26, 2016, 12:00:00

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.


More From » javascript

 Answers
15

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; }




[#59913] Wednesday, November 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
payne

Total Points: 527
Total Questions: 108
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;