To check whether a String contains a substring you can:
# Method 1: Using includes() function
The String.includes() function in Javascript allows you to check if a string includes a specified substring. This is a useful function to know when you need to check if a string contains a certain word or phrase.
const str = "Devsheet";
const subStr = "evs";
if (str.includes(subStr)) {
console.log("Included");
} else {
console.log("Not included");
}
Output
Included
The above code is checking if the string "Devsheet" includes the substring "evs". If it does, it will print "Included" to the console. Otherwise, it will print "Not included".
# Method 2: Using indexOf() function
If you need to check if a string includes a certain substring in JavaScript, you can use the indexOf() method. This method returns the index of the first occurrence of the substring, or -1 if the substring is not found.
const str = "Devsheet";
const subStr = "evs";
if (str.indexOf(subStr) !== -1) {
console.log("Included");
} else {
console.log("Not included");
}
Output
Included
In the above code example, we are using String.indexOf() function to check whether a string contains a substring.
These were some code examples that can be used to check whether a string includes a substring or not. We explained different methods in order to do that. If you have more methods for the same then you can also contribute here.
0 Comments