Code not running in IE 11, works fine in Chrome

Bhushan Dhamdhere picture Bhushan Dhamdhere · Jun 16, 2015 · Viewed 106.8k times · Source

The following code can be run without a problem in Chrome, but throws the following error in Internet Explorer 11.

Object doesn't support property or method 'startsWith'

I am storing the element's ID in a variable. What is the issue?

Answer

Oka picture Oka · Jun 16, 2015

String.prototype.startsWith is a standard method in the most recent version of JavaScript, ES6.

Looking at the compatibility table below, we can see that it is supported on all current major platforms, except versions of Internet Explorer.

╔═══════════════╦════════╦═════════╦═══════╦═══════════════════╦═══════╦════════╗
║    Feature    ║ Chrome ║ Firefox ║ Edge  ║ Internet Explorer ║ Opera ║ Safari ║
╠═══════════════╬════════╬═════════╬═══════╬═══════════════════╬═══════╬════════╣
║ Basic Support ║    41+ ║     17+ ║ (Yes) ║ No Support        ║    28 ║      9 ║
╚═══════════════╩════════╩═════════╩═══════╩═══════════════════╩═══════╩════════╝

You'll need to implement .startsWith yourself. Here is the polyfill:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}