码迷,mamicode.com
首页 > Web开发 > 详细

js 仿phptrim

时间:2016-04-06 18:37:47      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

 function trims(){
    this.init = function(myarguments){
        if(arguments.length===0){return false;}
        this.arg = myarguments;
        this.len = this.arg.length;
        if(this.len>0){ this.str = String(this.arg[0]); }
        if(this.len>1){ this.thechar = this.arg[1]; }
        if(typeof this.thechar==‘undefined‘){
            this.rg_l = new RegExp("^(\\s|\\u00A0)+");
            this.rg_r = new RegExp("\\S");
        }else{
            this.rg_l = new RegExp("^("+this.thechar+")+");
            this.rg_r = new RegExp("[^"+this.thechar+"]{1}");    
        }        
    };
    if (typeof trims._initialized == "undefined") {
        trims.prototype.ltrim = function() {
          this.str = this.str.replace(this.rg_l,‘‘);
        };
        trims.prototype.rtrim = function() {
            for(var i=this.str.length-1; i>=0; i--){
                if(this.rg_r.test(this.str.charAt(i))){  
                    this.str = this.str.substring(0, i+1);  
                    break;
                }
            }
            if(i===-1){this.str = ‘‘;}
        };
        trims._initialized = true;
    }  
};
var trimsobj = new trims();
function trim(){
    trimsobj.init(arguments);
    trimsobj.ltrim();
    trimsobj.rtrim();
    return trimsobj.str;
}
function rtrim(){
    trimsobj.init(arguments);
    trimsobj.rtrim();
    return trimsobj.str;
}
function ltrim(){
    trimsobj.init(arguments);
    trimsobj.ltrim();
    return trimsobj.str;
}

 

js 仿phptrim

标签:

原文地址:http://www.cnblogs.com/iidf/p/5360329.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!