簡體   English   中英

JS:在IE11中,字符串方法endsWith()不起作用

[英]JS: In IE11, string method endsWith() is not working

當我在IE11中嘗試this.form.name.endsWith("$END$")時,出現以下錯誤。

Object doesn't support property or method 'endsWith'

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

您可以改用填充劑

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

如此MDN所示 ,IE11不支持String.endsWith 您可以使用polyfill - 它將對endsSith的支持添加到String對象上 - 或者使用現有的JavaScript函數,例如String.matchRegExp.test

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

在IE11中沒有實現的目的。 你必須使用像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;
  };
}

我更喜歡一個shim cdn,因為我不需要擔心另一個開發者破壞js。 對於Wordpress,請使用此選項。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM