Given a String and a substring, the task is to check whether a string contains a substring or not in JavaScript. It can be useful in data processing, and filtering. If string contains a substring, then it display “Substring found!” otherwise display “Substring not found!” in console.
Examples
Input: str = "Hello World", substr = "Hello"
Output: Substring found!
Input: str = "JavaScript Program", substr = "JS"
Output: Substring not found!
Approach 1: Using indexOf() Method
The indexOf() method returns the position of the first occurrence of a specified substring within a string. If the substring is not found, it returns -1.
const str = "Hello world"; const substr = "Hello"; if (str.indexOf(substr) !== -1) { console.log("Substring found!"); } else { console.log("Substring not found!"); }
Output:
Substring found!
Approach 2: Using includes() Method
The includes() method checks whether a string contains a specified string (substring) or not. If string contains the substring, then it returns True, otherwise returns False.
const str = "Hello world!"; const substr = "Hello"; if (str.includes(substr)) { console.log("Substring found!"); } else { console.log("Substring not found!"); }
Output:
Substring found!
Approach 3: Using search() Method
The search() method searches a string against a regular expression, and returns the index (position) of the first match. If match not found, it returns -1.
const str = "Hello world!"; const substr = "world"; if (str.search(substr) !== -1) { console.log("Substring found!"); } else { console.log("Substring not found!"); }
Output:
Substring found!
Approach 4: Using RegExp Test
Regular expressions provide powerful pattern matching capabilities in JavaScript. You can use the test() method of a regular expression to check whether a string contains a substring.
const str = "Hello world!"; const substr = /world/; if (substr.test(str)) { console.log("Substring found!"); } else { console.log("Substring not found!"); }
Output:
Substring found!
Approach 5: Using ES6 includes() with Template Literals
In ES6, template literals allow for easy string interpolation. You can use them with the includes() method to check for substrings.
const str = "Hello world!"; const substr = "world"; if (`${str}`.includes(substr)) { console.log("Substring found!"); } else { console.log("Substring not found!"); }
Output:
Substring found!