In this tutorial, you’ll see a couple of ways to check if string contains substring using JavaScript.
Other tutorials in JavaScript Array series.
- Array Manipulation Using JavaScript Filter Method
- Array Manipulation Using JavaScript Map Method
- How to Remove Duplicates from JavaScript Array
- How To Loop Through An Array In JavaScript
- How To Remove Element From JavaScript Array
Using indexOf
You can use the String.indexOf method to find a substring in a string. indexOf methods returns a index greater than 0 if the substring is present in the string. If the substring is not found it will return -1.
Here is a code which demonstrate the same :
var position = 'codehandbook'.indexOf('hand')
console.log('substring starts at index ', position)
The above code will display the following output:
// output
"substring starts at index " 4
So if indexOf method returns -1 the substring is not found and if it returns a value greater than -1 the substring is found.
Using RegExp
You can use regular expressions to check if a string contains substring. For this to work you need to create a regular expression using your search string and test it against the main string. Here is the JavaScript code which shows the same :
var mainString = 'codehandbook'
var substr = /hand/
var found = substr.test(mainString)
if(found){
console.log('Substring found !!')
} else {
console.log('Substring not found !!')
}
As seen in the above code, you have converted the search term into a regular expression and used the test method to test if the substring if found.
Using Includes
You can check if a string contains substring using the includes method. It returns true if the substring is found and false if the substring is not found. Here is a JavaScript code sample :
var found = 'codehandbook'.includes('hand')
if(found){
console.log('Substring found !!')
} else {
console.log('Subtring not found !!')
}
The above code will have the following output :
// output
"Substring found !!"
Wrapping It Up
In this tutorial, you learnt different methods to check if a string contains substring. Have you used any other approach for finding the substring ? Do let us know your thoughts in the comments below.