rajausman haider
rajausman haider

Reputation: 580

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?

Upvotes: 11

Views: 18592

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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;
}

Upvotes: 17

Ali
Ali

Reputation: 1383

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>

Upvotes: 0

Muhammad Qasim
Muhammad Qasim

Reputation: 1712

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

Upvotes: 1

Related Questions