In JavaScript String Contains article, I have covered how to check a JavaScript string contains another string.JavaScript is not having contains() method. Mozilla supports contains() method 19.0+ onwards. But other browsers don’t support this method.
We can use String.indexOf() or String.search() functions to implement contains() function.
String.indexOf() – returns the position of a substring, returns -1 if not found.
String.search() – returns the position of a substring using regular expression, returns -1 if not found.
Below are the different string contains examples and their performance.
//1.Using indexOf, greater than -1 function contains(r,s){ return r.indexOf(s) > -1; } //2.Using indexOf, not equal to -1 function contains(r,s){ return r.indexOf(s) !== -1; } //3.Using indexOf, bool not with bitwise not function contains(r,s){ return !!~r.indexOf( s ); } //4.Using search(), greater than -1 function contains(r,s){ return r.search(s) > -1; } //5.Using search(), not equal to -1 function contains(r,s){ return r.search(s) !== -1; } //6.Using search(), bool not with bitwise not function contains(r,s){ return !!~r.search( s ); }
Using jsperf.com, we can find the performance of each function. After some trails, Below is the fastest JavaScript string contains function.
You can also perform tests here: http://jsperf.com/hg-string-contains
Function Prototype:
if(!String.prototype.contains) { String.prototype.contains = function (str) { return (this.indexOf(str) !== -1); }; }
How to use it:
var str ='javascript string contains performance. which one is best'; if(str.contains('best')) { alert("String found"); } else { alert("String not found"); }
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf