JavaScript endsWith在IEv10中不起作用? [英] JavaScript endsWith is not working in IEv10?

查看:65
本文介绍了JavaScript endsWith在IEv10中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to compare two strings in JavaScript using endsWith(), like

var isValid = string1.endsWith(string2);

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

It's working fine in Google Chrome and Mozilla. When comes to IE it's throwing a console error as follows

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

如何解决?

推荐答案

方法 < IE中不支持code> endsWith() 。在此处查看浏览器兼容性

您可以使用 MDN文档

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

这篇关于JavaScript endsWith在IEv10中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆