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

cpp*_*ner 6 javascript browser internet-explorer-11

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

Object doesn't support property or method 'endsWith'
Run Code Online (Sandbox Code Playgroud)

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

Moh*_*ham 8

你可以使用 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;
    };
}
Run Code Online (Sandbox Code Playgroud)

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


Jos*_*chi 2

在 IE11 中没有实现endsWith。你必须使用像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;
  };
}
Run Code Online (Sandbox Code Playgroud)