How to useArray.reduce() and Array.concat() Methods in Javascript
In this approach, The substringFunction splits input, then reduce() accumulates substrings by slicing the string. Array.from() creates substrings progressively, and concat() merges them into the final array.
Syntax:
function substringFunction(input) {
return input.split('').reduce((substrings, _, i) =>
substrings.concat(Array.from(
{ length: input.length - i },
(_, j) => input.slice(i, i + j + 1))),
[]
);
};
Example: In this example we are using the above-explained approach.
function substringFunction(input) {
return input.split('').reduce((substrings, _, i) =>
substrings.concat(Array.from(
{ length: input.length - i },
(_, j) => input.slice(i, i + j + 1))),
[]
);
}
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.