我尝试使用endsWith()比较JavaScript中的两个字符串,比如
var isValid = string1.endsWith(string2);
它在Google Chrome和Mozilla中运行良好。当它来到IE时它会抛出一个控制台错误如下
SCRIPT438: Object doesn't support property or method 'endsWith'
我该如何解决?
答案 0 :(得分:17)
IE中不支持 endsWith()
方法。检查browser compatibility here。
您可以使用从MDN documentation获取的填充选项:
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;
};
}
答案 1 :(得分:11)
我找到了最简单的答案,
您需要做的就是定义原型
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
答案 2 :(得分:2)
扩展原生JavaScript对象的原型通常是不好的做法。见这里 - Why is extending native objects a bad practice?
你可以使用这样一个跨浏览器的简单检查:
var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length))
答案 3 :(得分:0)
对旧问题的反应:
详细介绍IE11中endsWith()
的替代方法。
为避免string1 =“ a”,string2 =“ bc”;会返回true:
var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length) && string1.lastIndexOf(string2) >= 0);