11

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?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
rajausman haider
  • 570
  • 2
  • 10
  • 20

3 Answers3

17

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;
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

includes is not supported in Internet Explorer (or Opera)

Instead you can use 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)

Try the following:

var href = jQuery(this).attr('href');

if(href.indexOf('#') > -1) //this will true if the string contains #
{
   // action
}

This is supported by all browsers. This is a good read for your issue :)

Community
  • 1
  • 1
Muhammad Qasim
  • 1,622
  • 14
  • 26
0

Firstly you can check. Because IE does not support includes: MDN Reference

You can use like this. Yes, I know this is VanillaJS way. If you work cross browser use this way to avoid errors.:

var btn = document.querySelector('button')
var link = document.querySelector('a')
var isIE = window.navigator.userAgent.indexOf('Triden') > -1

btn.addEventListener("click", function() {
 
  var isHash = (!isIE) ? link.href.includes('#') : link.href.indexOf('#') > -1
  alert(isHash)
}, false)
<button>Control hash</button>
<hr />

<a href="http://somesite.com/#/GetUsers">Users</a>
Ali
  • 1,358
  • 3
  • 21
  • 32