【问题标题】:JS: In IE11, string method endsWith() is not workingJS:在 IE11 中,字符串方法 endsWith() 不起作用
【发布时间】:2019-03-13 02:46:22
【问题描述】:

当我在 IE11 中尝试 this.form.name.endsWith("$END$") 时,出现以下错误。

Object doesn't support property or method 'endsWith'

在 Chrome 中,它工作正常。 IE11中是否有任何替代字符串方法

【问题讨论】:

  • String.prototype.endsWith = "".endsWith || function(s){return !this.split(s).pop();};
  • 供将来参考...查看 MDN 文档 - 它会告诉您现代 javascript 方法是否与尼安德特人浏览器兼容

标签: javascript browser internet-explorer-11


【解决方案1】:

你可以改用 polyfill

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

【讨论】:

  • 您的链接已失效
【解决方案2】:

在 IE11 中没有实现 endWith。您将不得不使用像 mdn 中的 polyfill

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, position) {
      var subjectString = this.toString();
      if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
        position = subjectString.length;
      }
      position -= searchString.length;
      var lastIndex = subjectString.indexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
  };
}

【讨论】:

    【解决方案3】:

    正如在hereMDN 上所述,IE11 不支持String.endsWith。您可以使用 polyfill - 它在 String 对象上添加对 endsWith 的支持 - 或使用现有的 JavaScript 函数,例如 String.matchRegExp.test

    this.form.name.match(/\$END\$$\)
    

    【讨论】:

      【解决方案4】:

      我更喜欢 shim cdn,因为我不需要担心其他开发人员会破坏 js。 对于 Wordpress,使用这个。

      wp_enqueue_script( 'polyfill', 'https://cdn.polyfill.io/v2/polyfill.min.js' , false, '2.0.0', true);
      

      【讨论】:

        猜你喜欢
        • 2014-09-07
        • 1970-01-01
        • 2016-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-13
        • 1970-01-01
        • 2015-10-20
        相关资源
        最近更新 更多