我正在尝试使用endsWith() 比较JavaScript 中的两个字符串,例如
var isValid = string1.endsWith(string2);
它在 Google Chrome 和 Mozilla 中运行良好。当涉及 IE 时,它会抛出控制台错误,如下所示
SCRIPT438: Object doesn't support property or method 'endsWith'
我该如何解决?
Method endsWith() https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWithIE 中不支持。查看浏览器兼容性在这里 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith#Browser_compatibility.
您可以使用来自的polyfill选项MDN 文档 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith#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;
};
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)