Algorithm


  1. Input:

    • Accept the main string (mainString) and the substring (subString) as input.
  2. Initialization:

    • Initialize a variable (isSubstringFound) to false. This variable will be used to track whether the substring is found in the main string.
  3. Iterate Over the Main String:

    • Use a loop to iterate over each character in the main string.
    • For each character, check whether the substring matches the characters starting from the current position in the main string.
  4. Substring Matching:

    • If a match is found, set isSubstringFound to true and break out of the loop.
  5. Output:

    • After the loop, check the value of isSubstringFound.
    • If isSubstringFound is true, print or return a message indicating that the substring is present in the main string.
    • If isSubstringFound is false, print or return a message indicating that the substring is not found in the main string.

 

Code Examples

#1 Code Example- Check String with includes()

Code - Javascript Programming

// program to check if a string contains a substring

// take input
const str = prompt('Enter a string:');
const checkString = prompt('Enter a string that you want to check:');

// check if string contains a substring
if(str.includes(checkString)) {
    console.log(`The string contains ${checkString}`);
} else {
    console.log(`The string does not contain ${checkString}`);
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: JavaScript is fun
Enter a string that you want to check: fun
The string contains fun

#2 Code Example- Check String with indexOf()

Code - Javascript Programming

// program to check if a string contains a substring

// take input
const str = prompt('Enter a string:');
const checkString = prompt('Enter a string that you want to check:');

// check if string contains a substring
if(str.indexOf(checkString) !== -1) {
    console.log(`The string contains ${checkString}`);
} else {
    console.log(`The string does not contain ${checkString}`);
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: JavaScript is fun
Enter a string that you want to check: fun
The string contains fun
Advertisements

Demonstration


JavaScript Program to Check Whether a String Contains a Substring-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way