mehrandvd mehrandvd - 2 months ago 14
Javascript Question

string.contains() doesn't exist while working in chrome

I have a code like:

var valid = viewName.contains('/');


which works fine in firefox browser. But in chrome it is
undefined
. Why is that so? Is it true that chrome has not such a method for string?

Is it OK to use
indexOf
instead of
contains
, is it supported in all browsers?

Answer

Browser compatibility of String.contains()

String.indexOf() is what I use and it will work fine.

  var strIndex = viewName.indexOf('/');
  if(strIndex == -1) {
     //string not found
  } else {
    //string found
  }

But, just in case you want to have a contains() function, you can add it to String as below:

 if(!('contains' in String.prototype)) {
       String.prototype.contains = function(str, startIndex) {
                return -1 !== String.prototype.indexOf.call(this, str, startIndex);
       };
 }

var valid = viewName.contains('/');
if(valid) {
  //string found
} else {
  //string not found
}
Comments