How do I check if a string contains a substring in JavaScript?
Benjamin C
benjamin c profile pic

To check if a string contains a substring in JavaScript, you can use various methods provided by the String API. Here's a step-by-step guide on how to achieve this: 1. Create a string you want to search within:

1
2
3

   const string = "Hello, world!";
   

2. Use theincludes() method: Theincludes() method returns a boolean value indicating whether the string contains the specified substring. It is case-sensitive.

1
2
3
4
5

   const substring = "world";
   const containsSubstring = string.includes(substring);
   console.log(containsSubstring);  // Output: true
   

3. Use theindexOf() method: TheindexOf() method returns the index of the first occurrence of the specified substring within the string. If the substring is not found, it returns -1.

1
2
3
4
5

   const substring = "world";
   const index = string.indexOf(substring);
   console.log(index);  // Output: 7
   

4. Use thesearch() method: Thesearch() method searches for a specified substring within the string and returns the index of the first occurrence. If the substring is not found, it returns -1. Thesearch() method can also accept a regular expression.

1
2
3
4
5

   const substring = "world";
   const index = string.search(substring);
   console.log(index);  // Output: 7
   

5. Use a regular expression with thetest() method: Thetest() method of a regular expression can be used to check if the string contains a substring that matches the regular expression pattern. It returns a boolean value.

1
2
3
4
5

   const regex = /world/;
   const containsSubstring = regex.test(string);
   console.log(containsSubstring);  // Output: true
   

Choose the method that best fits your requirements and the specific context in which you need to check if a string contains a substring.