Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

includes() not working in IE

I am using the following code. It works perfectly in browsers such as Chrome, Firefox or Edge. However when I check in IE11 it does not work and breaks all the functionality.

var href = jQuery(this).attr('href');
if (href.includes('#')) {
  // action
}

I think includes() does not work in IE11. Is there a solution for this?

like image 432
rajausman haider Avatar asked Mar 31 '17 11:03

rajausman haider


People also ask

What is the alternative for 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.

How does include works in JavaScript?

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.

What is indexOf in JavaScript?

The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.


1 Answers

The issue is because includes() is unsupported in all versions of IE: MDN Reference

Instead you can use the much more widely supported indexOf():

var href = $(this).attr('href');
if (href.indexOf('#') != -1) {
  // action
}

You could also prototype this to add the includes() method to IE:

String.prototype.includes = function(match) {
  return this.indexOf(match) !== -1;
}
like image 58
Rory McCrossan Avatar answered Sep 22 '22 11:09

Rory McCrossan