Code not running in IE 11, works fine in Chrome

前端 未结 8 1208
春和景丽
春和景丽 2020-12-04 17:16

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

相关标签:
8条回答
  • 2020-12-04 17:35

    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;
      };
    }
    
    0 讨论(0)
  • 2020-12-04 17:39

    I also recently faced the prob. I solved using ^ which is similar to startwith in jquery. Say,

    var str = array[a].id;
    if (str.startsWith('REP')) {..........}
    

    we can use

    if($("[id^=str]").length){..........}
    

    Here, str is id of element.

    0 讨论(0)
  • 2020-12-04 17:44

    text.indexOf("newString") is the best method instead of startsWith.

    Example:

    var text = "Format";
    if(text.indexOf("Format") == 0) {
        alert(text + " = Format");
    } else {
        alert(text + " != Format");
    }
    
    0 讨论(0)
  • 2020-12-04 17:47

    While the post of Oka is working great, it might be a bit outdated. I figured out that lodash can tackle it with one single function. If you have lodash installed, it might save you a few lines.

    Just try:

    import { startsWith } from lodash;
    

    . . .

        if (startsWith(yourVariable, 'REP')) {
             return yourVariable;        
        return yourVariable;
           }      
         }
    
    0 讨论(0)
  • 2020-12-04 17:49

    If this is happening in Angular 2+ application, you can just uncomment string polyfills in polyfills.ts:

    import 'core-js/es6/string';
    
    0 讨论(0)
  • 2020-12-04 17:55

    As others have said startsWith and endsWith are part of ES6 and not available in IE11. Our company always uses lodash library as a polyfill solution for IE11. https://lodash.com/docs/4.17.4

    _.startsWith([string=''], [target], [position=0])
    
    0 讨论(0)
提交回复
热议问题