How to check whether a string contains a substring in JavaScript?


You can easily add a contains method to String with this statement:

String.prototype.contains = function(it) { return this.indexOf(it) != -1; };

Note: see the comments below for a valid argument for not using this. My advice: use your own judgement.


if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; }

Usually I would expect a String.contains() method, but there doesn't seem to be one.

What is a reasonable way to check for this?

Another option of doing this is:

You can use the match function, that is, something like:

x = "teststring";

if (x.match("test")) {
     // Code

match() can also work with regular expression :

x = "teststring";

if (x.match(/test/i)) {
     // Code

To collect some kind of valid solutions:

var stringVariable = "some text";
var findString = "text";

//using `indexOf()`
var containResult1 = stringVariable.indexOf(findString) != -1;
document.write(containResult1+', ');

//using `lastIndexOf()`
var containResult2 = stringVariable.lastIndexOf(findString) != -1;
document.write(containResult2+', ');

//using `search()`
var containResult3 = != -1;
document.write(containResult3+', ');
//using `split()`
var containResult4 = stringVariable.split(findString)[0] != stringVariable;

You can use jQuery's :contains selector.


Check it here: contains-selector

The easyest way is indeed using indexOf. To just check a string string for a substring substr you can use this method:

string = "asdf";
substr = "as";
alert(string.indexOf(substr) == -1 ? false : true);

As you wanted the function string.contains(), you can implement it yourself like this:

String.prototype.contains = function(test) {
    return this.indexOf(test) == -1 ? false : true;

Now you can use this ecen shorter method to check if a string contains a special substring:

string = "asdf";

Here is a JSFiddle as well.

var index = haystack.indexOf(needle);

You were looking for .indexOfMDN.

indexOf is going to return an index to the matched substring. The index will correlate to where the substring starts. If there is no match, a -1 is returned. Here is a simple demo of that concept:

var str = "Hello World"; // For example, lets search this string,
var term = "World"; // for the term "World",
var index = str.indexOf(term); // and get its index.
if (index != -1) { // If the index is not -1 then the term was matched in the string,
  alert(index); // and we can do some work based on that logic. (6 is alerted)

JavaScript code to use the contains method in an array:

        <h2>Use of contains() method</h2>
            Array.prototype.contains = function (element) {
                for (var i = 0; i < this.length; i++) {
                    if (this[i] == element) {
                        return true;
                return false;
            arr1 = ["Rose", "India", "Technologies"];
            document.write("The condition is "+arr1.contains("India")+"<br>");

    <b>[If the specified element is present in the array, it returns true otherwise
    returns false.]</b>


In the given code the contains method determines whether the specified element is present in the array or not. If the specified element is present in the array, it returns true, otherwise it returns false.

There is a sleek and better way to do this and it is using the (BitWise NOT) operator.

if(~"John".indexOf("J")) {
else {
  alert("Not Found");

The Bitwise Not converts "x" into -(x + 1) so, if the x turns out -1 from indexOf method.then it will be converted into -( -1 + 1) = -0 which is a falsy value .

A common way to write a contains method in JavaScript is:

if (!String.prototype.contains) {
    String.prototype.contains = function (arg) {
        return !!~this.indexOf(arg);

The bitwise negation operator (~) is used to turn -1 into 0 (falsey), and all other values will be non-zero (truthy).

The double boolean negation operators are used to cast the number into a boolean.

If you were looking for an alternative to write the ugly -1 check, you prepend a ~ tilde instead.

if (~haystack.indexOf('needle')) alert('found');

Joe Zimmerman - you'll see that using ~ on -1 converts it to 0. The number 0 is a falsey value, meaning that it will evaluate to false when converted to a Boolean. That might not seem like a big insight at first, but remember functions like indexOf will return -1 when the query is not found. This means that instead of writing something similar to this:

if (someStr.indexOf("a") >= 0) {
  // Found it
} else  {
  // Not Found

You can now have fewer characters in your code so you can write it like this:

if (~someStr.indexOf("a")) {
  // Found it
} else  {
  // Not Found

More details here

Simple workaround

if (!String.prototype.contains) {
  String.prototype.contains= function() {
    return String.prototype.indexOf.apply(this, arguments) !== -1;

you can use in the following way

"hello".contains("he") // true
"hello world".contains("lo w")//true
"hello world".contains("lo wa")//false
"hello world".contains(" ")//true
"hello world".contains("  ")//false

MDN reference


 var str = "My big string contain apples and oranges";
 var n = str.indexOf("apples"); 
 alert(n); //will alert 22, -1 if not found


  <p>My big string contain apples and oranges</p>
  alert($("p:contains(apples)")[0] != undefined); //will alert true if found

You could use the JavaScript search() method.

Syntax is:

It returns the position of the match, or -1 if no match is found.

See examples there: jsref_search

You don't need a complicated regular expression syntax. If you are not familiar with them a simple"title") will do. If you want your test to be case insensitive, then you should do