Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 314
mehrandvd Avatar asked Oct 05 '13 09:10

mehrandvd


People also ask

How do I check if a string contains?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do you check if a string contains a string in JavaScript?

To check if a substring is contained in a JavaScript string:Call the indexOf method on the string, passing it the substring as a parameter - string. indexOf(substring) Conditionally check if the returned value is not equal to -1. If the returned value is not equal to -1 , the string contains the substring.

How do you check if a string starts with another string 6 14?

You can use ECMAScript 6's String. prototype. startsWith() method.

How do you check if a string starts with a substring in node JS?

The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false .


2 Answers

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
}
like image 200
Rajesh Avatar answered Oct 21 '22 22:10

Rajesh


Support for this, in Firefox and Chrome too, is now disabled by default. If you land here looking for an up to date answer, you can view the reason why, and the new method name (which is String.includes) here.

Try:

yourString.includes('searchString')

like image 30
GrayedFox Avatar answered Oct 21 '22 21:10

GrayedFox