How to useNested Loops in Javascript
In this approach,we are using nested loops, iterate through input string. Capture substrings from each character to end, appending to accumulate all possible substrings.
Syntax:
for (let i = 0; i < input.length; i++) {
for (let j = i + 1; j <= input.length; j++) {
substrings.push(input.slice(i, j));
}
};
Example: In this approach we are using the above-explained approach.
function substringFunction(input) {
let substrings = [];
for (let i = 0; i < input.length; i++) {
for (let j = i + 1; j <= input.length; j++) {
substrings.push(input.slice(i, j));
}
}
return substrings;
}
let str1 = "abc";
let result = substringFunction(str1);
console.log(result);
Output
[ 'a', 'ab', 'abc', 'b', 'bc', 'c' ]
How to Get All Substrings of the Given String in JavaScript ?
In this article, we are going to learn about getting all substrings of the given string by using javascript, Substrings of a string are contiguous sequences of characters obtained by selecting a range of characters from the original string. They can be of various lengths and positions within the string.
Example:
Input : abc
Output : [ 'a', 'ab', 'abc', 'b', 'bc', 'c' ]
There are several methods that can be used to get all substrings of the given string in JavaScript, which are listed below:
- Using recursive
- Using Array.reduce() and Array.concat()
- Using Nested Loops
We will explore all the above methods along with their basic implementation with the help of examples.