. Advertisement .
. Advertisement .
- Use the includes() function
- Use the indexOf() function
- Use the “logical NOT (!)” operator
Let’s follow the specific steps below.
Method 1: using the includes() function
This is the simplest and most basic method to check if a string includes a substring or not. This method is compatible with most browsers, except Internet Explorer, so users can easily use it.
“searchString” is a string you need to search for in “str”, “position” is the string position and usually defaults to 0.
The result returned when running the syntax is True if it contains the string and False if it does not.
Here is an example to make it easier for you to visualize:
Method 2: Using the “logical NOT (!)” operator
In simple terms, this will be the negative method of the includes() function. As you know, in the above method, if a string contains no substrings, includes() will return False. However, with the use of the logical NOT (!) operator, the result will be the opposite, which means that if the string does not contain a substring, the return result will be True.
Here is a specific example:
const str = 'IT tutoria'; // Use the includes() function console.log(str.includes('tutorial')); // false // Use the logical NOT (!) operator console.log(!str.includes('tutorial')); // true
Method 3: Using the indexOf() function
If your browser cannot use the above two methods, you can consider using this 3rd method. With the
indexOf() function, the result returned will be related to the index of the string, so you need to understand the theory of indexes.
Similarly, searchString is the Substring to search, and the position will default to 0.
var string = "tutoria"; var substring = "ria"; console.log(string.indexOf(substring) !== -1); // true
This function will return the result as the first occurrence of the string (starting at position 0); if the string is not found, it will return -1. If the Substring is found, it returns the index of the character that started the string.