In this article I will discuss how you can check if a string contains particular substring.
1. Prior JavaScript ES6, the conventional way to check if a string contains a substring was to use the string method indexOf that return -1 if the string does not contain the substring. If the substring is found, it returns the index of the character that starts the string. This method is supported by all browsers including Internet Explorer (IE).
var message= "Have a wonderful day.";
message.indexOf('wonderful') !== -1 // true
message.indexOf('wonderful') // 7
// Example: Check if message contains the string 'wonderful'
if(message.indexOf('wonderful') !== -1){
// message contains the string 'wonderful'
}
2. ES6/ES2015 has introduced a string method includes to check if a string contains substring.
Example:
var message= "Have a wonderful day.";
message.includes('wonderful') // true
// Example: With ES6
if(message.includes('wonderful')){
// message contains the string 'wonderful'
}
The includes method is supported by all modern browsers except IE.