JavaScript

Check if a String Contains a Substring in JavaScript2 min read

In JavaScript, checking if a string contains a substring is a common task that can be achieved in a number of ways. In this post, we will explore different methods to determine if a given string contains a substring.

Method 1: Using the includes() method The simplest and most straightforward method of checking if a string contains a substring is by using the includes() method. This method returns a boolean value indicating whether the string contains the specified substring.




Here’s an example:

Method 2: Using the indexOf() method Another method to check if a string contains a substring is by using the indexOf() method. This method returns the index of the first occurrence of the specified substring, or -1 if the substring is not found.

Here’s an example:

Method 3: Using the search() method The search() method is similar to the indexOf() method, but it supports regular expressions as well. If the substring is found, the method returns the index of the first occurrence of the substring, or -1 if the substring is not found.

Here’s an example:

Method 4: Using the match() method The match() method is used to search for a match between a regular expression and a string. If a match is found, the method returns an array containing all the matches, or null if no match is found.

Here’s an example:

In conclusion, these are some of the ways to check if a string contains a substring in JavaScript. The choice of method depends on the specific requirements of your project and your personal preferences.

Leave a Comment