To get all possible substrings of a string in JavaScript, you can use nested loops to iterate through each combination of start and end indices.
In this example,
str
with a value of 'Hello'
.substrings
to store all substrings.substring
method and add it to the substrings
array.substrings
array to the console.let str = 'Hello';
let substrings = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j <= str.length; j++) {
substrings.push(str.substring(i, j));
}
}
console.log('All substrings:', substrings);
All substrings: [ 'H', 'He', 'Hel', 'Hell', 'Hello', 'e', 'el', 'ell', 'ello', 'l', 'll', 'llo', 'l', 'lo', 'o' ]
In this tutorial, we learned How to get all the possible Substrings of a String in JavaScript language with well detailed examples.