Horje
JavaScript Program to Print all Substrings of a Given String

In this article, we will see how we can print all substrings of a given string in JavaScript language. We have provided an input string, from which we need to print all the possible substrings. Below we have stated the example for a better understanding of the problem statement:

Example:

Input: abc
Output: a
ab
abc
b
bc
c

To print all substrings of a given string in JavaScript, we have three different approaches, which we have stated below:

So, we will see all of the above approaches with its implementation:

Using substring() Method

The substring() method in JavaScript is used to get the substrings from the input string. We have used the 2 nested loops to specify the starting and ending indices of each of the substring and then the substrings are printed using substring() method.

Syntax:

string.substring([start,end])

Example: In this example, we will be printing all substrings of a given string in JavaScript using substring() method.

JavaScript
let str = "abcd";
let uniqueSub = new Set();

for (let i = 0; i < str.length; i++) {
    for (
        let j = i + 1;
        j <= str.length;
        j++
    ) {
        let substring = str.substring(
            i,
            j
        );
        if (!uniqueSub.has(substring)) {
            console.log(substring);
            uniqueSub.add(substring);
        }
    }
}

Output
a
ab
abc
abcd
b
bc
bcd
c
cd
d

Using slice() Method

The slice() method in JavaScript is also used to extract the substrings of the input string. Same as Apprach 1, we have used 2 nested loops to specify the starting and ending indices, and then we are printing the substrings using splice() method.

Syntax:

string.slice([start,end])

Example: In this example, we will be printing all substrings of a given string in JavaScript using sllice() method.

JavaScript
let str = "abcd";
let uniqueSub = new Set();

for (let i = 0; i < str.length; i++) {
    for (
        let j = i + 1;
        j <= str.length;
        j++
    ) {
        let substring = str.slice(i, j);
        if (!uniqueSub.has(substring)) {
            console.log(substring);
            uniqueSub.add(substring);
        }
    }
}

Output
a
ab
abc
abcd
b
bc
bcd
c
cd
d

Using String Concatenation

Syntax:

sub +=str[j];

Example: In this example, we will be printing all substrings of a given string in JavaScript using String Concatenation.

JavaScript
let str = "abcd";
let uniqueSub = new Set();
for (let i = 0; i < str.length; i++) {
    let substring = "";
    for (
        let j = i;
        j < str.length;
        j++
    ) {
        substring += str[j];
        uniqueSub.add(substring);
    }
}
uniqueSub.forEach((substring) => {
    console.log(substring);
});

Output
a
ab
abc
abcd
b
bc
bcd
c
cd
d

Using Array or No Builtin Functions

The array is used to store the substrings and also we are checking for the substrings by using loop and conditional statement rather than using any builtin method. This apporach is completely raw appraoach, as no builtin methods are used here.

Syntax:

let array = [];
for(loop_condtion) {
//statements
}
if(condition)
{
//statements
}

Example: In this example, we will be printing all substrings of a given string in JavaScript using Array or without using Builtin functions.

JavaScript
function subStrings(str) {
    let substrings = [];
    for (
        let start = 0;
        start < str.length;
        start++
    ) {
        for (
            let end = start + 1;
            end <= str.length;
            end++
        ) {
            let sub = "";
            for (
                let i = start;
                i < end;
                i++
            ) {
                sub += str[i];
            }
            let uniqueSub = true;
            for (
                let j = 0;
                j < substrings.length;
                j++
            ) {
                if (
                    sub ===
                    substrings[j]
                ) {
                    uniqueSub = false;
                    break;
                }
            }
            if (uniqueSub) {
                substrings.push(sub);
                console.log(sub);
            }
        }
    }
}
subStrings("abcd");

Output
a
ab
abc
abcd
b
bc
bcd
c
cd
d

Using Regular Expressions

Regular expressions (regex) offer a powerful and concise way to search for patterns in strings. We can use regex to generate all possible substrings of a given string by using capturing groups within a loop. This approach involves using the match method to find all matches of the pattern in the string.

Example: In this example, we will be printing all substrings of a given string in JavaScript using regular expressions.

JavaScript
function getAllSubstrings(str) {
    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));
        }
    }
    return substrings;
}

function regexApproach(str) {
    let pattern = new RegExp(".{" + str.length + "}", "g");
    let matches = [];
    for (let i = 1; i <= str.length; i++) {
        pattern = new RegExp(".{1," + i + "}", "g");
        matches.push(...str.match(pattern));
    }
    return matches;
}

// Example usage:
let inputString = "abc";
let result = regexApproach(inputString);
console.log(result);

Output
[ 'a', 'b', 'c', 'ab', 'c', 'abc' ]





Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Create an Autoplay Carousel using HTML CSS and JavaScript Create an Autoplay Carousel using HTML CSS and JavaScript
Bookmark in Google Chrome Browser Bookmark in Google Chrome Browser
JavaScript Program to Get the Dimensions of an Image JavaScript Program to Get the Dimensions of an Image
What is Firefox Developer Edition ? What is Firefox Developer Edition ?
Less Than Symbol in Maths | Meaning &amp; Examples of Less Than Sign Less Than Symbol in Maths | Meaning &amp; Examples of Less Than Sign

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12