js中浏览器兼容startsWith 、endsWith 函数

时间:2022-05-09 19:19:12

在做js开发的时候用到了startsWith函数时,发现各个浏览器不兼容问题,因为对开发来说,chrome浏览器最好用,就一直在chrome浏览器中使用这两个函数没有任何问题,但在ie浏览器访问就直接报错,因为ie没有这两个函数,要么修改方法,换别的方法,但是一两个还好改,多了就不好改,这个时候就只能扩充String方法。

先判断浏览器是否有当前方法,没有则添加

if (typeof String.prototype.startsWith !== 'function') {
String.prototype.startsWith = function(prefix) {
return this.slice(0, prefix.length) === prefix;
};
} if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
String.prototype.startsWith = function(str) {
if (!str || str.length > this.length)
return false;
if (this.substr(0, str.length) == str)
return true;
else
return false;
return true;
} // 使用正则表达式
String.prototype.startsWith = function(str) {
var reg = new RegExp("^" + str);
return reg.test(this);
} //测试ok,直接使用str.endsWith("abc")方式调用即可
String.prototype.endsWith = function(str) {
var reg = new RegExp(str + "$");
return reg.test(this);
}