1

Recently I was writing logic in JavaScript and I wrote something like this

var str="hello world";

if(str.contains("w"))
    //do something
else
   //do anotherthing

I thought it was working fine until I ran the page in Chrome. In Chrome I'm getting an error of contains is not a function.

Although I got rid of this by modifying the logic as

var str="hello world";
if(str.indexOf("w")!=-1)
    //do something
else
   //do another thing

is contains not a standard ECMAScript function? I'm able to see contains through intellisense in Firefox but not in Chrome.

While testing these in different browsers I noticed in the console that

String.subString/indexOf //not showing in chrome but works in Firefox

instead str.substring/indexOf works in chrome

Aren't these methods are part of standard String object?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Ein2012
  • 1,103
  • 1
  • 13
  • 33
  • 3
    `.includes` is the standard name of the method. `.contains` was preferred, but it broke websites because a once popular library (Mootools) had defined the string's `.contains` method with different semantics. – Rob W May 21 '15 at 08:39
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes – CodingIntrigue May 21 '15 at 08:40

3 Answers3

1

It is explained here. String.prototype.contains is not a part of EsmaScript 5.1, which is currently releases.

Community
  • 1
  • 1
Ilya Skiba
  • 21
  • 4
  • 1
    As of June, 2015, [*ECMAScript ed 6*](http://ecma-international.org/ecma-262/6.0/index.html) is the current standard. ;-) – RobG Jun 25 '15 at 20:18
1

This is a duplicate of this question.

I will repost the answer here for convenience.

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

Community
  • 1
  • 1
GrayedFox
  • 2,350
  • 26
  • 44
0

.contains() is not part of the standard string objects

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Prasanjit Dey
  • 5,914
  • 3
  • 13
  • 15