JavaScript的endsWith在IEv10中无法正常工作?

17

我正在尝试使用JavaScript的endsWith()方法比较两个字符串,例如:

var isValid = string1.endsWith(string2);

在Google Chrome和Mozilla中运行良好,但在IE浏览器中会抛出控制台错误,如下所示:

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

我该怎么解决这个问题?
4个回答

22

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

最好知道这个脚本可以放置在任何地方。理想情况下,它应该在页面加载时加载,以便它可以为所有其他函数提供支持。 - David Brossard
在这里找到简化的答案:https://dev59.com/7VoU5IYBdhLWcg3wV2C8 - Sivaprasad derangula

18
我找到了最简单的答案,
你只需要定义原型即可。
 if (!String.prototype.endsWith) {
   String.prototype.endsWith = function(suffix) {
     return this.indexOf(suffix, this.length - suffix.length) !== -1;
   };
 }

赞。不管怎样,我认为 string.indexOf(suffix, string.length - suffix.length) !== -1; 就足够了,因为改变原型是一个坏主意。 - Marco Sulla

2

通常不推荐扩展本地JavaScript对象的原型。请参见此处 - 为什么扩展本地对象是一种不好的做法?

您可以使用像这样的简单检查,它将跨浏览器工作:

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

这将无法通过基本测试用例,例如 string1 = "a",string2 = "bc"; 将返回 true。 - Drenai

0
回应旧问题: 探讨IE11中 endsWith() 的替代方案。
为了避免 string1 = "a",string2 = "bc" 返回 true:
var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length) && string1.lastIndexOf(string2) >= 0);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接