This article example describes the method of JS to determine whether a string contains a substring. Share it for your reference. The details are as follows:
In our daily front-end development, we often encounter judging whether a string contains a substring. Here we will explore some solutions to this requirement and use them correctly. Ideally, what we are 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 are probably the easiest thing we think of. If it contains a substring, it returns an index greater than or equal to 0, otherwise it returns -1, which does not meet our ideal situation.
The code copy is as follows: var str = "My blog name is Benjamin-focused on front-end development and user experience",
substr = "Benjamin";
function isContains(str, substr) {
return str.indexOf(substr) >= 0;
}
//true
console.log(isContains(str, substr));
2. String.prototype.search
We thought of the String.prototype.search method, because the parameter of the search method is a regular expression, it is the same as the case of indexOf.
The code copy is as follows: var str = "My blog name is Benjamin-focused on front-end development and user experience",
substr = "Benjamin";
function isContains(str, substr) {
return new RegExp(substr).test(str);
}
//true
console.log(isContains(str, substr));
This method looks better than the indexOf method, which directly returns true or false, and the method name test is more semantic than indexOf.
3. String.prototype.contains
The code copy is as follows: var str = "My blog name is Benjamin-focused on front-end development and user experience",
substr = "Benjamin";
function isContains(str, substr) {
return str.contains(substr);
}
//true
console.log(isContains(str, substr));
This method is currently only supported by Firefox and is still in the ECMAScript 6 draft. This method meets the ideal situation mentioned above. For details, please click here. If you want to use the contains method, you can refer to the third-party library string.js, click here to download string.js. Source code implementation:
Copy the code as follows: contains: function(ss) {
return this.s.indexOf(ss) >= 0;
},
Other methods are to be supplemented. . .
Of course, in terms of performance issues, which method to use is still to be tested. Interested friends may wish to test it yourself.
I hope this article will be helpful to everyone's JavaScript programming.