Home > Article > Web Front-end > js method to determine whether a string contains a substring_javascript skills
The example in this article describes how js determines whether a string contains a substring. Share it with everyone for your reference. The details are as follows:
In our daily front-end development, we often encounter the problem of determining whether a string contains a certain substring. Here we will explore some methods to solve this requirement and use them correctly. Ideally, what we're looking for is a method that matches our purpose (if x contains y) and returns true or false.
1. String.prototype.indexOf and String.prototype.lastIndexOf
These two methods may be the easiest for us to think of. If it contains a substring, it will return an index greater than or equal to 0, otherwise it will return -1, which does not meet our ideal situation.
We thought of the String.prototype.search method. Since the parameter of the search method is a regular expression, it is the same as indexOf.
This method looks better than the indexOf method. This method directly returns true or false. At the same time, the method name test is more semantic than indexOf.
3. String.prototype.contains
I hope this article will be helpful to everyone’s JavaScript programming design.