There are different ways to check if a string contains a specific substring in JavaScript. In JavaScript, you can check if a string contains a specific substring using the includes() method or by using the indexOf() method.
Using the includes() method:
- Returns true if the substring is found, false otherwise.
- Case-sensitive.
- The includes() method doesn’t provide any information about where a match occurs
const string = "Hello, how are you!"; const substring = "you"; if (string.includes(substring)) { console.log("The string contains the substring."); } else { console.log("The string does not contain the substring."); }
Using the indexOf() method:
- Returns the index of the first occurrence of the substring, or -1 if not found.
- Also case-sensitive.
const mainString = "Hello, world!"; const substringToCheck = "world"; if (mainString.indexOf(substringToCheck) !== -1) { console.log("Main string contains the substring"); } else { console.log("Main string does not contain the substring"); }
The search that includes() performs is case-sensitive. If you want a case-insensitive search, you can call toLowerCase() on both strings first:
const searchString = 'CONTAINS'; const fullText = 'You want to check if one string contains another substring.'; if (fullText.toLowerCase().includes(searchString.toLowerCase())) { // The search string was found console.log("Main string contains the substring"); }
Both methods return a boolean value (true or false) indicating whether the substring is present in the main string. Note that includes() is more straightforward for simple existence checks, while indexOf() is more versatile as it can also provide the index of the substring within the string (or -1 if not found).