js 常用工具方法

1、格式化字符串

String.prototype.format = function () {
    let args = arguments;
    return this.replace(/\{(\d+)\}/g,(item,idx) => {
        return args[idx];
    });
};

 

2、格式化日期

Date.prototype.format = function (fmt) {
    let o = {
        'M+': this.getMonth() + 1,
        'd+': this.getDate(),
        'H+': this.getHours(),
        'm+': this.getMinutes(),
        's+': this.getSeconds(),
        'q+': Math.floor((this.getMonth() + 3) / 3),
        'S': this.getMilliseconds()
    };
    if (/(y+)/.test(fmt)){
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (let k in o){
        if (new RegExp('(' + k + ')').test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
    }
    return fmt;
};

 

3、替换字符串

String.prototype.replaceAll = function (src, dec) {
    return this.replace(new RegExp(src, 'gm'), dec);
};

 

4、去掉前后空格

String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, '');
};

 

5、生成随机整数

function getRandomInt(min,max){
    return Math.floor(Math.random()*(max-min+1))+min;
}

 

6、生成验证码

function getValidCode(len){
    let strSource = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+'abcdefghijklmnopqrstuvwxyz'+'0123456789';
    let res = '',idx = 0;
    for(let i=0;i<len;i++){
        idx = Math.floor(Math.random()*strSource.length);
        res += strSource.substring(idx,idx+1);
    }
    return res;
}

 

7、生成GUID

function getGUID(){
    let curtime = new Date().getTime();
    if (window.performance && typeof window.performance.now === 'function') {
        curtime += performance.now();
    }
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let rad = (curtime + Math.random() * 16) % 16 | 0;
        curtime = Math.floor(curtime / 16);
        return (c === 'x' ? rad : (rad & 0x3 | 0x8)).toString(16);
    });
}

 

8、判断数据类型

function varType(input){
    let tof = Object.prototype.toString.call(input);
    return tof.match(/\[object (.*?)\]/)[1].toLowerCase();
};

['Null','Undefined','Object','Array','String','Number','Boolean','Function','RegExp'].forEach(function(curVal){
    varType['is' + curVal] = function(input){
        return varType(input) === curVal.toLowerCase();
    };
});

 

posted @ 2019-12-09 17:14  laoq112  阅读(351)  评论(0)    收藏  举报