在做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); }
如对本文有疑问, 点击进行留言回复!!
selenium + ajax抓取英雄联盟全部英雄的详细信息及多线程保存全部皮肤图片到本地
网友评论