美文网首页前后端知识交流分享
字符串简单的位数补齐功能

字符串简单的位数补齐功能

作者: Trytodo_zbs | 来源:发表于2018-07-16 16:23 被阅读5次

很多时候我们会碰到需要保证字符串位数为多少位的清空
例如:保留时间的月为两位,高位补0
编号按顺序递增前面补0

下面是一段简单的写在String的原型上面的方法
限制了补位的字符串大小,当字符串大小本身大于限制长度的时候不做处理(也可以做处理,看需求)

    /**
     * 为String添加toFix方法,用于补充填充规则
     * 暂时先限制填充字符只能是一个字符串
     * 设定长度以1个字符串为单位
     * @param {String} fill 填充字符
     * @param {Number} len  限制长度
     * @param {String} dir  填充方向,分往前填充left,往后填充right
     * */
    String.prototype.toFix=function(fill,len,dir){
        var getLength=function(str){
            ///<summary>获得字符串实际长度,中文2,英文1</summary> 
            ///<param name="str">要获得长度的字符串</param>  
            var realLength = 0, len = str.length, charCode = -1;
            for (var i = 0; i < len; i++) {
                charCode = str.charCodeAt(i);
                if (charCode >= 0 && charCode <= 128) realLength += 1;
                else realLength += 2;
            }
            return realLength;
        }
        var str=this;
        if(getLength(fill)==1){
            if(typeof len=="number" && len%1 === 0){
                if(getLength(str)<len){
                    while(getLength(str)<len){
                        str = dir=="left"?fill+str:str+fill;
                    }
                }else{console.warn("字符串长度超出设定长度");}
            }else{console.warn("长度必须是整数")}
        }else{console.warn("填充字符的长度必须为1")}
        return str;
    }
    //功能分支,向右/向后 填充...返回填充后的数据
    String.prototype.toFixRight=function(fill,len){
        return this.toFix(fill,len,"right");
    }
    //功能分支,向左/向前 填充...返回填充后的数据
    String.prototype.toFixLeft=function(fill,len){
        return this.toFix(fill,len,"left");
    }

相关文章

网友评论

    本文标题:字符串简单的位数补齐功能

    本文链接:https://www.haomeiwen.com/subject/keubpftx.html