How to check whether a string contains a substring in JavaScript?
let str = "Hello, world!";
let substr = "world";
console.log(str.includes(substr)); // Output: true
You can also use the indexOf()
method which returns the index of the first occurrence of the substring in the string, or -1 if the substring is not found. Here’s an example:
let str = "Hello, world!";
let substr = "world";
// Output: true
console.log(str.indexOf(substr) !== -1);
Or use search
method that returns the index of the first match or -1 if not found
let str = "Hello, world!";
let substr = "world";
// Output: true
console.log(str.search(substr) !== -1);
Both includes()
and indexOf()
methods are case sensitive and both are work fine on String objects.