How to check whether a string contains a substring in JavaScript?

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

MethodCase-Sensitive?ReturnsRegex Support?Browser Support
includes()✅ YesBoolean (true/false)❌ NoES6+ (modern browsers)
indexOf()✅ YesIndex or -1❌ NoAll
Regex test()ConfigurableBoolean (true/false)✅ YesAll
search()✅ YesIndex or -1✅ YesAll
match()✅ YesArray or null✅ YesAll

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) or indexOf().
  • Case-insensitive check: Regex with i flag.
  • Pattern matching: Regex (test(), match(), or search()).

Example:

// Modern and clean
if (str.includes("substring")) { ... }

// Case-insensitive regex check
if (/substring/i.test(str)) { ... }

Leave a Reply

Your email address will not be published. Required fields are marked *