Learn how to find if a string contains a substring in javascript using indexOf, Includes, and Search method in javascript.

Check if a string contains a substring
Check if a string contains a substring

If you’re working with strings in JavaScript, you may need to check if a particular substring exists within a given string.

Fortunately, JavaScript provides several methods that allow you to easily check for the presence of a substring.

In this context, we’ll explore the three most commonly used methods to check if a string contains a substring in JavaScript:

  • indexOf()
  • includes()
  • search().

These methods can be used to search for a single character, a word, or a group of characters in a string.

1. Using IndexOf() Method

indexOf method returns the index of the first occurrence of a specified substring within a given string.

If the substring is not found, the method returns -1.

The indexOf() method is a commonly used way to check if a string contains a substring in JavaScript.

const string = "Hello world!";
const substring = "world";

if (string.indexOf(substring) !== -1) {
  console.log("Substring found!");
} else {
  console.log("Substring not found.");
}

2. Using includes() method

Includes method returns a boolean value indicating whether a specified substring is present within a given string or not.

If the substring is found, the method returns true; if not, it returns false.

The includes() method is similar to the indexOf() method but returns a Boolean value rather than an index.

const string = "Hello world!";
const substring = "world";

if (string.includes(substring)) {
  console.log("Substring found!");
} else {
  console.log("Substring not found.");
}

This method searches for a specified substring within a given string and returns the index of the first occurrence.

If the substring is not found, the method returns -1.

The search() method is similar to the indexOf() method but allows the use of regular expressions in the search string.

const string = "Hello world!";
const substring = "world";

if (string.search(substring) !== -1) {
  console.log("Substring found!");
} else {
  console.log("Substring not found.");
}

These are the top 3 ways to find if a string contains a substring in javascript

See also  Get the Source Code Of Any Webpage using Puppeteer