我正在尝试使用endsWith()比较JavaScript中的两个字符串
var isValid = string1.endsWith(string2);
它在Google Chrome和Mozilla中运行良好。来到IE时它会抛出一个控制台错误,如下所示
SCRIPT438: Object doesn't support property or method 'endsWith'
我该如何解决?
IE中不支持方法endsWith()
。检查browser compatibility here。
您可以使用从MDN documentation获取的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对象的原型通常是不好的做法。看到这里 - Why is extending native objects a bad practice?
你可以使用这样一个跨浏览器的简单检查:
var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length))