1. Introduction
There are several methods to check if one string contains another in JavaScript. We listed here some of them, if you know more, please feel free do write that in comments.
2. 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.
3. 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.
4. match method
The match() method accepts regular expressions only and will return Array with input property if original string match given parameter.
5. RegExp method
With regular expressions in JavaScript 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.
6. Conclusion
In this article we showcased several methods to check if one string contains another in JavaScript. Is up to you which method you will choose.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}