Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.includes() not working in Internet Explorer

Tags:

javascript

People also ask

Does IE support include?

includes was not supported in IE. I had to write substitute of this function. This function basically did 2 things: check if element is in array.

What we can use instead of includes in JavaScript?

indexOf() The Array#indexOf() function is a common alternative to includes() . The indexOf() function returns the first index in the array at which it found valueToFind , or -1 otherwise.

Can I use includes JavaScript?

includes() used as a generic methodincludes() method is intentionally generic. It does not require this value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates includes() method called on the function's arguments object.

How includes work in JS?

In JavaScript, includes() method determines whether a string contains the given characters within it or not. This method returns true if the string contains the characters, otherwise, it returns false.


String.prototype.includes is, as you write, not supported in Internet Explorer (or Opera).

Instead you can use String.prototype.indexOf. #indexOf returns the index of the first character of the substring if it is in the string, otherwise it returns -1. (Much like the Array equivalent)

var myString = 'this is my string';
myString.indexOf('string');
// -> 11

myString.indexOf('hello');
// -> -1

MDN has a polyfill for includes using indexOf: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill

EDIT: Opera supports includes as of version 28.

EDIT 2: Current versions of Edge supports the method. (as of 2019)


Or just put this in a Javascript file and have a good day :)

String.prototype.includes = function (str) {
  var returnValue = false;

  if (this.indexOf(str) !== -1) {
    returnValue = true;
  }

  return returnValue;
}

includes() is not supported by most browsers. Your options are either to use

-polyfill from MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes

or to use

-indexof()

var str = "abcde";
var n = str.indexOf("cd");

Which gives you n=2

This is widely supported.


Problem:

Try running below(without solution) from Internet Explorer and see the result.

console.log("abcde".includes("cd"));

Solution:

Now run below solution and check the result

if (!String.prototype.includes) {//To check browser supports or not
  String.prototype.includes = function (str) {//If not supported, then define the method
    return this.indexOf(str) !== -1;
  }
}
console.log("abcde".includes("cd"));