欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-25 19:42:03
在做js开发的时候用到了startsWith函数时,发现各个浏览器不兼容问题,因为对开发来说,chrome浏览器最好用,就一直在chrome浏览器中使用这两个函数没有任何问题,但在ie浏览器访问就直接报错,因为ie没有这两个函数,要么修改方法,换别的方法,但是一两个还好改,多了就不好改,这个时候就只 ......

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