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

问题描述 投票:1回答:4

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

Object doesn't support property or method 'endsWith'

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

javascript browser internet-explorer-11
4个回答
3
投票

您可以改用填充剂

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


1
投票

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

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

0
投票

在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;
  };
}

0
投票

我更喜欢一个shim cdn,因为我不需要担心另一个开发者破坏js。对于Wordpress,请使用此选项。

wp_enqueue_script( 'polyfill', 'https://cdn.polyfill.io/v2/polyfill.min.js' , false, '2.0.0', true);
© www.soinside.com 2019 - 2024. All rights reserved.