15

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?

mehrandvd
  • 8,806
  • 12
  • 64
  • 111

4 Answers4

40

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
}
Rajesh
  • 3,743
  • 1
  • 24
  • 31
  • Your polyfill is broken - the specification of contains is different. See MDN. – georg Oct 05 '13 at 10:23
  • 2
    Just an FYI: The ES6 Draft Standard changed `.contains()` to be named `.includes()` `.contains()` will be removed from Firefox eventually and replaced with the standard `.includes`. Currently Chrome provides `.includes`. – Ray Suelzer Apr 12 '15 at 04:22
  • Using polyfill to provide functionality which already exists natively in the browser is, IMO, bad practise. Also, this answer is now out of date. Perhaps the author could update it? – GrayedFox Apr 03 '17 at 08:26
  • 2
    at the time the answer was added, contains was not natively supported in all browsers – Rajesh Apr 03 '17 at 11:11
9

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')

GrayedFox
  • 2,350
  • 26
  • 44
2

.contains was entirely removed in FireFox 48 as the documentation, currently last updated on 22.07.2016, reveals. The function .includes does what .contains did before, though.

Benefits: .includes is also supported by Chrome.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes for reference.

I was going to post this as comment but unregistered people can only write full answers. (facepalm)

Chris
  • 21
  • 1
1

The contains method of strings was first added to V8, then included in Chrome after version 30.0.1583.0, but it is disabled by default. This feature is only available if you enable "experimental JavaScript features" at chrome://flags/#enable-javascript-harmony.

Rob W
  • 341,306
  • 83
  • 791
  • 678