How to useRecursive Approach in Javascript
In this approach, the Recursive function generates all substrings. Split the string into the first character and rest, then combine them.
Syntax:
function SubstringFunction(input) {
if (input.length === 0) {
return [''];
}
let first = input[0];
let restSubstrings = SubstringFunction(input.slice(1));
let substrings = restSubstrings.map(sub => first + sub);
return [...substrings, ...restSubstrings];
}
Example: In this example we are using the above-explained approach.
function SubstringFunction(input) {
if (input.length === 0) {
return [''];
}
let first = input[0];
let restSubstrings = SubstringFunction(input.slice(1));
let substrings = restSubstrings.map(sub => first + sub);
return [...substrings, ...restSubstrings];
}
let str1 = "abc";
let result = SubstringFunction(str1);
console.log(result);
Output
[ 'abc', 'ab', 'ac', 'a', 'bc', 'b', '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.
Contact Us