SoFunction
Updated on 2025-03-03

js method to determine whether a string contains a substring

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 methods to solve 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. and

These two methods are probably the easiest to think of. If you include a substring, it returns an index greater than or equal to 0, otherwise it returns -1, which does not meet our ideal situation.

Copy the codeThe code 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 (substr) >= 0;
}
 
//true
(isContains(str, substr));

two,

We thought of a method, because the parameter of the search method is a regular expression, it is the same as the case of indexOf.

Copy the codeThe code 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
(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.

three,

Copy the codeThe code 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 (substr);
}
 
//true
(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. Please provide detailsClick here. If you want to use the contains method, you can refer to the third-party library. Click here to view this sitedownload. Source code implementation:
Copy the codeThe code is as follows:
contains: function(ss) {
  return (ss) >= 0;
},

Other methods are to be supplemented. . .

Of course, in terms of performance issues, which method to use is faster remains to be tested. Interested friends may wish to test it yourself.

I hope this article will be helpful to everyone's JavaScript programming.