

This article introduces the basics of the includes() method for each prototype, as well as exploring the differences between the two. This method accepts a search value as a parameter, and returns true if the value is either contained in the array on which it is called, or if it exists as a substring of the string object on which it is called.

If the index is out of range, it returns an empty string. charAt(index) – Returns a string representing the character at the specified index.match(searchValue) – Finds the searchValue, a regular expression, within a given string and returns an array containing the matches.lastIndexOf(searchValue) – Returns the index position of the last occurrence of searchValue inside a string.search(regExp) – Returns the index of the first match between regExp and the string.Other search methods you can consider include: You can also include the position at which to begin searching the string for the substring. const str = 'This is my example string!'

If the substring is not found, it returns -1. The indexOf() method is also case sensitive, and returns the index position of the first occurrence of the substring within the string. If you want to begin searching at position 2, you would write: console.log(str.includes(substr, 2)) To work around this, you can convert the string to lower case using toLowerCase() as follows: console.log(str.toLowerCase().includes(substr)) įurthermore, a position can also be passed as an argument to specify the position at which to begin searching the string for the substring. Note that includes() performs a case-sensitive search. This will return true if the substring is found, or false if not.Ĭonsider the code example below: const str = 'This is my example string!' You can use JavaScript’s includes() method to check whether a string contains a substring. We’ll take a look at two methods: includes() and indexOf(). There are a number of ways you could approach this problem. What are the different ways to do this? The Solution You want to check whether a string contains a substring in JavaScript.
