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:
1 2 3 4 5 6 | let str = "Hello World"; let substring = "Hello"; console.log(str.includes(substring)); // returns true |
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:
1 2 3 4 5 6 | let str = "Hello World"; let substring = "Hello"; console.log(str.indexOf(substring) !== -1); // returns true |
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:
1 2 3 4 5 6 | let str = "Hello World"; let substring = "Hello"; console.log(str.search(substring) !== -1); // returns true |
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:
1 2 3 4 5 6 | let str = "Hello World"; let substring = "Hello"; console.log(str.match(substring) !== null); // returns true |
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.