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

在做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; }; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsxpsz.html