Check if string includes a substring Javascript (Multiple Methods)
If you're working with strings in JavaScript, it's often useful to know whether or not a string includes a particular substring. For example, you might want to check if a string contains a URL or a specific word. In this article, we will show you different methods to check that.
Check if string includes a substring Javascript
To check whether a String contains a substring you can:
- Get the string and substring variables.
- Use string.includes(sub_string) - It will return true if the substring exists in the string else false.
# 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.
Conclusion
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.
- Check if Array includes String(Case Insensitive) Javascript
- How to Check If an Array Includes an Object
- Methods to check empty array using javascript
- Methods to shuffle an array using javascript
- Efficiently Remove the Last Element from an Array in JavaScript [6 Methods Explained]
- Check if a string is Palindrome or not using Javascript
- JavaScript ES6 filtering object with multiple params