Coder Perfect

In Internet Explorer 11, the code does not run, but it does in Chrome.

Problem

In Chrome, the following code works fine, but in Internet Explorer 11, it fails with the following error.

The ID of the element is saved in a variable. What exactly is the problem?

Asked by Bhushan Dhamdhere

Solution #1

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

According to the compatibility table below, it is supported on all current main platforms, with the exception of Internet Explorer versions.

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

You’ll need to add.startsWith to your code. The polyfill is as follows:

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

Answered by Oka

Solution #2

Instead of startsWith, text.indexOf(“newString”) is the better way.

Example:

var text = "Format";
if(text.indexOf("Format") == 0) {
    alert(text + " = Format");
} else {
    alert(text + " != Format");
}

Answered by Jona

Solution #3

If this happens in an Angular 2+ app, simply uncomment string polyfills in the polyfills. ts:

import 'core-js/es6/string';

Answered by Vitaliy Ulantikov

Solution #4

StartsWith should be replaced with:

yourString.indexOf(searchString, position) // where position can be set to 0

This will work with all browsers, including Internet Explorer.

Position can be set to 0 to match strings from the beginning, i.e. the 0th position.

Answered by Harshit Pant

Solution #5

As others have stated, startsWith and endsWith are ES6 features that are not present in Internet Explorer 11. For IE11, we always utilize the lodash library as a polyfill solution. https://lodash.com/docs/4.17.4

_.startsWith([string=''], [target], [position=0])

Answered by mbokil

Post is based on https://stackoverflow.com/questions/30867172/code-not-running-in-ie-11-works-fine-in-chrome