JavaScript endsWith在IEv10中不起作用?

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

var isValid = string1.endsWith(string2); 

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

 SCRIPT438: Object doesn't support property or method 'endsWith' 

我该如何解决?

方法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; }; } 

我找到了最简单的答案,

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

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

扩展原生JavaScript对象的原型通常是不好的做法。 请参阅此处 – 为什么扩展本机对象是一种不好的做法?

你可以使用这样一个跨浏览器的简单检查:

 var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length))