我正在尝试使用JavaScript的endsWith()方法比较两个字符串,例如:
var isValid = string1.endsWith(string2);
在Google Chrome和Mozilla中运行良好,但在IE浏览器中会抛出控制台错误,如下所示:
SCRIPT438: Object doesn't support property or method 'endsWith'
我该怎么解决这个问题?
我正在尝试使用JavaScript的endsWith()方法比较两个字符串,例如:
var isValid = string1.endsWith(string2);
在Google Chrome和Mozilla中运行良好,但在IE浏览器中会抛出控制台错误,如下所示:
SCRIPT438: Object doesn't support property or method 'endsWith'
方法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;
};
}
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通常不推荐扩展本地JavaScript对象的原型。请参见此处 - 为什么扩展本地对象是一种不好的做法?
您可以使用像这样的简单检查,它将跨浏览器工作:
var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length))
string1 = "a",string2 = "bc"
; 将返回 true。 - DrenaiendsWith()
的替代方案。var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length) && string1.lastIndexOf(string2) >= 0);