JavaScript endsWith 在 IEv10 中不工作?
JavaScript endsWith is not working in IEv10?
我正在尝试使用 endsWith() 比较 JavaScript 中的两个字符串,例如
var isValid = string1.endsWith(string2);
它在 Google Chrome 和 Mozilla 中运行良好。当涉及到 IE 时,它会抛出如下控制台错误
SCRIPT438: Object doesn't support property or method 'endsWith'
我该如何解决?
方法endsWith()
not supported in IE. Check 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))
对旧问题的反应:
详细说明 endsWith()
在 IE11 中的替代方案。
为了避免string1 = "a", string2 = "bc"; return 会是真的吗:
var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length) && string1.lastIndexOf(string2) >= 0);
我正在尝试使用 endsWith() 比较 JavaScript 中的两个字符串,例如
var isValid = string1.endsWith(string2);
它在 Google Chrome 和 Mozilla 中运行良好。当涉及到 IE 时,它会抛出如下控制台错误
SCRIPT438: Object doesn't support property or method 'endsWith'
我该如何解决?
方法endsWith()
not supported in IE. Check 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))
对旧问题的反应:
详细说明 endsWith()
在 IE11 中的替代方案。
为了避免string1 = "a", string2 = "bc"; return 会是真的吗:
var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length) && string1.lastIndexOf(string2) >= 0);