To check whether a string contains a substring in JavaScript, you can use the includes()
method of the String
object. The includes()
method returns a boolean value indicating whether the string contains the specified substring.
Here’s an example of how to use the includes()
method to check for a substring:
const str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.includes('fox')); // true
console.log(str.includes('cat')); // false
You can also use the indexOf()
method to check for a substring. The indexOf()
method returns the index of the substring within the string, or -1
if the substring is not found.
Here’s an example of how to use the indexOf()
method to check for a substring:
const str = 'The quick brown fox jumps over the lazy dog.';
if (str.indexOf('fox') !== -1) {
console.log('The string contains the substring');
} else {
console.log('The string does not contain the substring');
}
Keep in mind that both the includes()
and indexOf()
methods are case-sensitive, so they will not match substrings that have a different case.
const str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.includes('Fox')); // false
console.log(str.indexOf('Fox')); // -1