Algorithm
-
Input:
- Accept the main string (
mainString
) and the substring (subString
) as input.
- Accept the main string (
-
Initialization:
- Initialize a variable (
isSubstringFound
) to false. This variable will be used to track whether the substring is found in the main string.
- Initialize a variable (
-
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.
-
Substring Matching:
- If a match is found, set
isSubstringFound
to true and break out of the loop.
- If a match is found, set
-
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.
- After the loop, check the value of
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
Enter a string: JavaScript is fun
Enter a string that you want to check: fun
The string contains 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
Enter a string: JavaScript is fun
Enter a string that you want to check: fun
The string contains fun
Enter a string that you want to check: fun
The string contains fun
Demonstration
JavaScript Program to Check Whether a String Contains a Substring-DevsEnv