JavaScript endsWith在IEv10中不起作用?

Siv*_*ula 13 javascript jquery internet-explorer prototypejs

我正在尝试使用endsWith()比较JavaScript中的两个字符串

var isValid = string1.endsWith(string2);
Run Code Online (Sandbox Code Playgroud)

它在Google Chrome和Mozilla中运行良好.来到IE时它会抛出一个控制台错误,如下所示

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

我该如何解决?

Pra*_*lan 18

endsWith()IE中不支持的方法.检查浏览器兼容性.

您可以使用从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)


Siv*_*ula 12

我找到了最简单的答案,

您所需要做的就是定义原型

 if (!String.prototype.endsWith) {
   String.prototype.endsWith = function(suffix) {
     return this.indexOf(suffix, this.length - suffix.length) !== -1;
   };
 }
Run Code Online (Sandbox Code Playgroud)