Check for Substring in JavaScript
Given two strings, check if one string is substring of another.
- "bce" is substring of "abcde"
- "ae" is not substring of "abcde"
- Empty String is a substring of all strings
Using includes() - Most used and Simplest Method
The includes() method checks whether a string contains a substring.
let s = "abcde";
let res = s.includes("bcd");
console.log(res);
Output
true
Using indexOf() - Gives Index of First Occurrence as well
The indexOf() method returns the index of the first occurrence of a specified substring in a string. If the substring is not found, it returns -1.
let s = "Hello, world!";
let res = s.indexOf("world") !== -1;
console.log(res);
Output
true
Using Regular Expressions (RegExp)
Regular expressions can be used to check if a substring exists within a string by using the .test() method.
let s = "Hello, world!";
let pat = /world/;
let res = pat.test(s);
console.log(res);
Output
true
In this example, the regular expression /world/ checks for the presence of the word "world" in the string.
Which Approach is Better in Different Cases?
- includes() Method: The simplest and most readable approach. Use it when you need to check if a substring is present.
- indexOf() Method: Useful if you need the position of the substring, not just a Boolean check.
- Regular Expressions (RegExp): Use this method for more complex pattern matching, such as case-insensitive checks or partial matches.
Check Whether a String Contains a Substring in JavaScript - FAQs
Is the includes() method case-sensitive?
Yes, includes() is case-sensitive, so "Hello" and "hello" would be considered different.
What happens if the substring is not found with indexOf()?
If the substring is not found, indexOf() returns -1.
Can I perform a case-insensitive search with includes()?
No, includes() itself is case-sensitive, but you can convert both strings to the same case using toLowerCase() or toUpperCase().
Are regular expressions slower than includes()?
Regular expressions can be slower for simple searches, but they are more powerful for complex pattern matching.
How do I use includes() with an array of strings?
Use Array.prototype.some() in combination with includes() to check if any element in the array contains a specific substring.