In JavaScript, there are several ways to check if a string contains a substring. Here are the most common methods:
1. includes()
Method
The simplest and most modern approach. Returns true
if the substring exists, false
otherwise.
const str = "Hello, World!";
console.log(str.includes("World")); // true
console.log(str.includes("world")); // false (case-sensitive)
Notes:
- Case-sensitive.
- Available in ES6+ (not supported in very old browsers like IE).
2. indexOf()
Method
Returns the index of the substring’s first occurrence (-1
if not found).
const str = "Hello, World!";
console.log(str.indexOf("World") !== -1); // true
console.log(str.indexOf("world") !== -1); // false
Pros:
- Works in all browsers.
- Returns the position of the substring.
3. Regex with test()
Use a regular expression to check for a substring (supports case-insensitive searches).
const str = "Hello, World!";
console.log(/World/.test(str)); // true
console.log(/world/i.test(str)); // true (case-insensitive with `i` flag)
Use Cases:
- Complex pattern matching (e.g., partial words, case-insensitive checks).
4. search()
Method
Similar to indexOf()
, but accepts a regex and returns the match index.
const str = "Hello, World!";
console.log(str.search(/World/) !== -1); // true
5. match()
Method
Returns an array of matches or null
if no match is found.
const str = "Hello, World!";
console.log(str.match(/World/) !== null); // true
Key Differences
Method | Case-Sensitive? | Returns | Regex Support? | Browser Support |
---|---|---|---|---|
includes() | ✅ Yes | Boolean (true/false ) | ❌ No | ES6+ (modern browsers) |
indexOf() | ✅ Yes | Index or -1 | ❌ No | All |
Regex test() | Configurable | Boolean (true/false ) | ✅ Yes | All |
search() | ✅ Yes | Index or -1 | ✅ Yes | All |
match() | ✅ Yes | Array or null | ✅ Yes | All |
Case-Insensitive Check
Use regex with the i
flag for case-insensitive searches:
const str = "Hello, World!";
console.log(str.toLowerCase().includes("world")); // true (using toLowerCase)
console.log(/world/i.test(str)); // true (using regex)
When to Use Which?
- Simple check:
includes()
(modern) orindexOf()
. - Case-insensitive check: Regex with
i
flag. - Pattern matching: Regex (
test()
,match()
, orsearch()
).
Example:
// Modern and clean
if (str.includes("substring")) { ... }
// Case-insensitive regex check
if (/substring/i.test(str)) { ... }