Checking for Substring with includes() Method
JavaScript string.includes() method can be used to check whether a string contains a specified substring. It returns true if the substring is present. This method is case-sensitive.
Syntax:
string.includes(searchvalue, start)
Example: This example uses the includes() method of JavaScript to check for the substring in a string.
let str = "Hello there! Welcome to w3wiki";
let flag = str.includes("Geeks");
console.log(flag);
Output
true
Explanation:
The code checks if the string “Hello there! Welcome to w3wiki” contains the substring “Geeks”. It assigns the result of this check to the variable `flag` and logs it to the console.
How to check whether a string contains a substring in JavaScript ?
A substring is a portion of a string. It represents a sequence of characters extracted from a larger string. A substring can be as short as a single character or extend to multiple characters.
There are several approaches to check whether a string contains a substring or not:
Table of Content
- Checking for Substring with includes() Method
- Checking for Substring with test() Method
- Checking for Substring with match() Method
- Checking for Substring with indexOf() Method
- Checking for Substring with search() Method