There are several methods to check if one string contains another in JS. We listed here some of them, if you know more, please feel free do write it in comments.
1. indexOf method
The indexOf() method returns index of the first occurrence of searched string. If the value is not found it will return -1.
Keep in mind that indexOf() method is case sensitive.
It also has second parameter representing the index at which to start the search.
2. search method
The search() returns the position of the match, or -1 if no match is found. The search value can be string or a regular expression.
3. match method
The match() method accepts regular expressions only and will return Array with input property if original string match given parameter.
4. RegExp method
With regular expressions in JS you have two options to check if one string contains another:
- test() - method executes a search for a match between a regular expression and a specified string. Returns true or false,
- exec() - this method search for a match in a specified string. Returns a result array, or null if no match found.
As you can see those methods are very similar but their differ in return type.