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.
JavaScript
x
19
19
1
var theString = 'somerandomword',
2
allSubstrings = [];
3
4
getAllSubstrings(theString);
5
6
function getAllSubstrings(str) {
7
8
var start = 1;
9
10
for ( var i = 0; i < str.length; i++ ) {
11
12
allSubstrings.push( str.substring(start,i) );
13
14
}
15
16
}
17
18
console.log(allSubstrings)
19
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.
Advertisement
Answer
You need two nested loop for the sub strings.
JavaScript
1
13
13
1
function getAllSubstrings(str) {
2
var i, j, result = [];
3
4
for (i = 0; i < str.length; i++) {
5
for (j = i + 1; j < str.length + 1; j++) {
6
result.push(str.slice(i, j));
7
}
8
}
9
return result;
10
}
11
12
var theString = 'somerandomword';
13
console.log(getAllSubstrings(theString));
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }