JavaScript常用方法パッケージ

19656 ワード

1.タイプ判断
isString (o) { //     
    return Object.prototype.toString.call(o).slice(8, -1) === 'String'
}

isNumber (o) { //    
    return Object.prototype.toString.call(o).slice(8, -1) === 'Number'
}

isBoolean (o) { //  boolean
    return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean'
}

isFunction (o) { //    
    return Object.prototype.toString.call(o).slice(8, -1) === 'Function'
}

isNull (o) { //   null
    return Object.prototype.toString.call(o).slice(8, -1) === 'Null'
}

isUndefined (o) { //  undefined
    return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined'
}

isObj (o) { //    
    return Object.prototype.toString.call(o).slice(8, -1) === 'Object'
}

isArray (o) { //    
    return Object.prototype.toString.call(o).slice(8, -1) === 'Array'
}

isDate (o) { //    
    return Object.prototype.toString.call(o).slice(8, -1) === 'Date'
}

isRegExp (o) { //    
    return Object.prototype.toString.call(o).slice(8, -1) === 'RegExp'
}

isError (o) { //      
    return Object.prototype.toString.call(o).slice(8, -1) === 'Error'
}

isSymbol (o) { //  Symbol  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Symbol'
}

isPromise (o) { //  Promise  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Promise'
}

isSet (o) { //  Set  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Set'
}

isFalse (o) {
    if (!o || o === 'null' || o === 'undefined' || o === 'false' || o === 'NaN') return true
        return false
}

isTrue (o) {
    return !this.isFalse(o)
}

isIos () {
    var u = navigator.userAgent;
    if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {//    
        // return "Android";
        return false
    } else if (u.indexOf('iPhone') > -1) {//    
        // return "iPhone";
        return true
    } else if (u.indexOf('iPad') > -1) {//iPad
        // return "iPad";
        return false
    } else if (u.indexOf('Windows Phone') > -1) {//winphone  
        // return "Windows Phone";
        return false
    }else{
        return false
    }
}

isPC () { //   PC 
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

browserType(){
    var userAgent = navigator.userAgent; //      userAgent   
    var isOpera = userAgent.indexOf("Opera") > -1; //    Opera   
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //    IE   
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //    IE Edge     
    var isFF = userAgent.indexOf("Firefox") > -1; //    Firefox   
    var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //    Safari   
    var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //  Chrome   

    if (isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if(fIEVersion == 7) return "IE7"
        else if(fIEVersion == 8) return "IE8";
        else if(fIEVersion == 9) return "IE9";
        else if(fIEVersion == 10) return "IE10";
        else return "IE7  "//IE    
    }
    if (isIE11) return 'IE11';
    if (isEdge) return "Edge";
    if (isFF) return "FF";
    if (isOpera) return "Opera";
    if (isSafari) return "Safari";
    if (isChrome) return "Chrome";
}

checkStr (str, type) {
    switch (type) {
        case 'phone':   //    
            return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
        case 'tel':     //  
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
        case 'card':    //   
            return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
        case 'pwd':     //       ,   6~18  ,      、      
            return /^[a-zA-Z]\w{5,17}$/.test(str)
        case 'postal':  //    
            return /[1-9]\d{5}(?!\d)/.test(str);
        case 'QQ':      //QQ 
            return /^[1-9][0-9]{4,9}$/.test(str);
        case 'email':   //  
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
        case 'money':   //  (   2 )
            return /^\d*(?:\.\d{0,2})?$/.test(str);
        case 'URL':     //  
            return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
        case 'IP':      //IP
            return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
        case 'date':    //    
            return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
        case 'number':  //  
            return /^[0-9]$/.test(str);
        case 'english': //  
            return /^[a-zA-Z]+$/.test(str);
        case 'chinese': //  
            return /^[\u4E00-\u9FA5]+$/.test(str);
        case 'lower':   //  
            return /^[a-z]+$/.test(str);
        case 'upper':   //  
            return /^[A-Z]+$/.test(str);
        case 'HTML':    //HTML  
            return /])*>/.test(str);
        default:
            return true;
    }

    //         
    isCardID(sId) {
        if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) {
            alert('              ')
            return false
        }
        //     
        var aCity={11:"  ",12:"  ",13:"  ",14:"  ",15:"   ",21:"  ",22:"  ",23:"   ",31:"  ",32:"  ",33:"  ",34:"  ",35:"  ",36:"  ",37:"  ",41:"  ",42:"  ",43:"  ",44:"  ",45:"  ",46:"  ",50:"  ",51:"  ",52:"  ",53:"  ",54:"  ",61:"  ",62:"  ",63:"  ",64:"  ",65:"  ",71:"  ",81:"  ",82:"  ",91:"  "};
        if(!aCity[parseInt(sId.substr(0,2))]) { 
            alert('         ')
            return false
        }

        //       
        var sBirthday=(sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2))).replace(/-/g,"/"),
            d = new Date(sBirthday)
        if(sBirthday != (d.getFullYear()+"/"+ (d.getMonth()+1) + "/" + d.getDate())) {
            alert('           ')
            return false
        }

        //        
        var sum = 0,
            weights =  [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
            codes = "10X98765432"
        for (var i = 0; i < sId.length - 1; i++) {
            sum += sId[i] * weights[i];
        }
        var last = codes[sum % 11]; //              
        if (sId[sId.length-1] != last) { 
            alert('          ')
            return false
        }

        return true
    }
}
  • Date
  • /**
     *      
     * 
     * @param  {time}   
     * @param  {cFormat}   
     * @return {String}    
     *
     * @example formatTime('2018-1-29', '{y}/{m}/{d} {h}:{i}:{s}') // -> 2018/01/29 00:00:00
     */
    formatTime(time, cFormat) {
        if (arguments.length === 0) return null
        if ((time + '').length === 10) {
            time = +time * 1000
        }
    
        var format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}', date
        if (typeof time === 'object') {
            date = time
        } else {
            date = new Date(time)
        }
    
        var formatObj = {
            y: date.getFullYear(),
            m: date.getMonth() + 1,
            d: date.getDate(),
            h: date.getHours(),
            i: date.getMinutes(),
            s: date.getSeconds(),
            a: date.getDay()
        }
        var time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
            var value = formatObj[key]
            if (key === 'a') return [' ', ' ', ' ', ' ', ' ', ' ', ' '][value - 1]
            if (result.length > 0 && value < 10) {
                value = '0' + value
            }
            return value || 0
        })
        return time_str
    }
    
    /**
     *            
     * 
     * @param  {time}   
     * @param  {len}   
     * @param  {direction}   :  1:     ;  2:     ;  3:          3
     * @return {Array}   
     * 
     * @example   getMonths('2018-1-29', 6, 1)  // ->  ["2018-1", "2017-12", "2017-11", "2017-10", "2017-9", "2017-8", "2017-7"]
     */
    getMonths(time, len, direction) {
        var mm = new Date(time).getMonth(),
            yy = new Date(time).getFullYear(),
            direction = isNaN(direction) ? 3 : direction,
            index = mm;
        var cutMonth = function(index) {
            if ( index <= len && index >= -len) {
                return direction === 1 ? formatPre(index).concat(cutMonth(++index)):
                    direction === 2 ? formatNext(index).concat(cutMonth(++index)):formatCurr(index).concat(cutMonth(++index))
            }
            return []
        }
        var formatNext = function(i) {
            var y = Math.floor(i/12),
                m = i%12
            return [yy+y + '-' + (m+1)]
        }
        var formatPre = function(i) {
            var y = Math.ceil(i/12),
                m = i%12
            m = m===0 ? 12 : m
            return [yy-y + '-' + (13 - m)]
        }
        var formatCurr = function(i) {
            var y = Math.floor(i/12),
                yNext = Math.ceil(i/12),
                m = i%12,
                mNext = m===0 ? 12 : m
            return [yy-yNext + '-' + (13 - mNext),yy+y + '-' + (m+1)]
        }
        //     
        var unique = function(arr) {
            if ( Array.hasOwnProperty('from') ) {
                return Array.from(new Set(arr));
            }else{
                var n = {},r=[]; 
                for(var i = 0; i < arr.length; i++){
                    if (!n[arr[i]]){
                        n[arr[i]] = true; 
                        r.push(arr[i]);
                    }
                }
                return r;
            }
        }
        return direction !== 3 ? cutMonth(index) : unique(cutMonth(index).sort(function(t1, t2){
            return new Date(t1).getTime() - new Date(t2).getTime()
        }))
    }
    
    /**
     *            
     * 
     * @param  {time}   
     * @param  {len}   
     * @param  {direction}   : 1:    ;  2:    ;  3:         3
     * @return {Array}   
     *
     * @example date.getDays('2018-1-29', 6) // -> ["2018-1-26", "2018-1-27", "2018-1-28", "2018-1-29", "2018-1-30", "2018-1-31", "2018-2-1"]
     */
    getDays(time, len, diretion) {
        var tt = new Date(time)
        var getDay = function(day) {
            var t = new Date(time)
            t.setDate(t.getDate() + day)
            var m = t.getMonth()+1
            return t.getFullYear()+'-'+m+'-'+t.getDate()
        }
        var arr = []
        if (diretion === 1) {
            for (var i = 1; i <= len; i++) {
                arr.unshift(getDay(-i))
            }
        }else if(diretion === 2) {
            for (var i = 1; i <= len; i++) {
                arr.push(getDay(i))
            }
        }else {
            for (var i = 1; i <= len; i++) {
                arr.unshift(getDay(-i))
            }
            arr.push(tt.getFullYear()+'-'+(tt.getMonth()+1)+'-'+tt.getDate())
            for (var i = 1; i <= len; i++) {
                arr.push(getDay(i))
            }
        }
        return diretion === 1 ? arr.concat([tt.getFullYear()+'-'+(tt.getMonth()+1)+'-'+tt.getDate()]) : 
            diretion === 2 ? [tt.getFullYear()+'-'+(tt.getMonth()+1)+'-'+tt.getDate()].concat(arr) : arr
    }
    
    /**
     * @param  {s}   
     * @return {String}     
     *
     * @example formatHMS(3610) // -> 1h0m10s
     */
    formatHMS (s) {
        var str = ''
        if (s > 3600) {
            str = Math.floor(s/3600)+'h'+Math.floor(s%3600/60)+'m'+s%60+'s'
        }else if(s > 60) {
            str = Math.floor(s/60)+'m'+s%60+'s'
        }else{
            str = s%60+'s'
        }
        return str
    }
    
    /*        */
    getMonthOfDay (time) {
        var date = new Date(time)
        var year = date.getFullYear()
        var mouth = date.getMonth() + 1
        var days
    
        //       ,             
        if (mouth == 2) {
            days = (year%4==0 && year%100==0 && year%400==0) || (year%4==0 && year%100!=0) ? 28 : 29
        } else if (mouth == 1 || mouth == 3 || mouth == 5 || mouth == 7 || mouth == 8 || mouth == 10 || mouth == 12) {
            //   :1,3,5,7,8,10,12  ,   .    31;
            days = 31
        } else {
            //    ,   :30.
            days = 30
        }
        return days
    }
    
    /*        */
    getYearOfDay (time) {
        var firstDayYear = this.getFirstDayOfYear(time);
        var lastDayYear = this.getLastDayOfYear(time);
        var numSecond = (new Date(lastDayYear).getTime() - new Date(firstDayYear).getTime())/1000;
        return Math.ceil(numSecond/(24*3600));
    }
    
    /*        */
    getFirstDayOfYear (time) {
        var year = new Date(time).getFullYear();
        return year + "-01-01 00:00:00";
    }
    
    /*        */
    getLastDayOfYear (time) {
        var year = new Date(time).getFullYear();
        var dateString = year + "-12-01 00:00:00";
        var endDay = this.getMonthOfDay(dateString);
        return year + "-12-" + endDay + " 23:59:59";
    }
    
    /*              */
    getDayOfYear (time) {
        var firstDayYear = this.getFirstDayOfYear(time);
        var numSecond = (new Date(time).getTime() - new Date(firstDayYear).getTime())/1000;
        return Math.ceil(numSecond/(24*3600));
    }
    
    /*              */
    getDayOfYearWeek (time) {
        var numdays = this.getDayOfYear(time);
        return Math.ceil(numdays / 7);
    }
    
    3.アラy
    /*            */
    contains (arr, val) {
        return arr.indexOf(val) != -1 ? true : false;
    }
    
    /**
     * @param  {arr}   
     * @param  {fn}     
     * @return {undefined}
     */
    each (arr, fn) {
        fn = fn || Function;
        var a = [];
        var args = Array.prototype.slice.call(arguments, 1);
        for(var i = 0; i < arr.length; i++) {
            var res = fn.apply(arr, [arr[i], i].concat(args));
            if(res != null) a.push(res);
        }
    }
    
    /**
     * @param  {arr}   
     * @param  {fn}     
     * @param  {thisObj} this  
     * @return {Array} 
     */
    map (arr, fn, thisObj) {
        var scope = thisObj || window;
        var a = [];
        for(var i = 0, j = arr.length; i < j; ++i) {
            var res = fn.call(scope, arr[i], i, this);
            if(res != null) a.push(res);
        }
        return a;
    }
    
    /**
     * @param  {arr}   
     * @param  {type} 1:       2:       3:  
     * @return {Array}
     */
    sort (arr, type = 1) {
        return arr.sort( (a, b) => {
            switch(type) {
                case 1:
                    return a - b;
                case 2:
                    return b - a;
                case 3:
                    return Math.random() - 0.5;
                default:
                    return arr;
            }
        })
    }
    
    /*  */
    unique (arr) {
        if ( Array.hasOwnProperty('from') ) {
            return Array.from(new Set(arr));
        }else{
            var n = {},r=[]; 
            for(var i = 0; i < arr.length; i++){
                if (!n[arr[i]]){
                    n[arr[i]] = true; 
                    r.push(arr[i]);
                }
            }
            return r;
        }
        //  :   else            2   '2',     indexOf     ,          。。。
        /*     
        if ( Array.hasOwnProperty('from') ) {
            return Array.from(new Set(arr))
        }else{
            var r = [], NaNBol = true
            for(var i=0; i < arr.length; i++) {
                if (arr[i] !== arr[i]) {
                    if (NaNBol && r.indexOf(arr[i]) === -1) {
                        r.push(arr[i])
                        NaNBol = false
                    }
                }else{
                    if(r.indexOf(arr[i]) === -1) r.push(arr[i])
                }
            }
            return r
        }
    
         */
    }
    
    /*        */
    union (a, b) {
        var newArr = a.concat(b);
        return this.unique(newArr);
    }
    
    /*        */
    intersect (a, b) {
        var _this = this;
        a = this.unique(a);
        return this.map(a, function(o) {
            return _this.contains(b, o) ? o : null;
        });
    }
    
    /*        */
    remove (arr, ele) {
        var index = arr.indexOf(ele);
        if(index > -1) {
            arr.splice(index, 1);
        }
        return arr;
    }
    
    /*            */
    formArray (ary) {
        var arr = [];
        if(Array.isArray(ary)) {
            arr = ary;
        } else {
            arr = Array.prototype.slice.call(ary);
        };
        return arr;
    }
    
    /*   */
    max (arr) {
        return Math.max.apply(null, arr);
    }
    
    /*   */
    min (arr) {
        return Math.min.apply(null, arr);
    }
    
    /*  */
    sum (arr) {
        return arr.reduce( (pre, cur) => {
            return pre + cur
        })
    }
    
    /*   */
    average (arr) {
        return this.sum(arr)/arr.length
    }
    
    
  • String文字列動作
  • /**
     *     
     * @param  {str}
     * @param  {type} 
     *       type:  1-      2-      3-    4-   
     * @return {String}
     */
    trim (str, type) {
        type = type || 1
        switch (type) {
            case 1:
                return str.replace(/\s+/g, "");
            case 2:
                return str.replace(/(^\s*)|(\s*$)/g, "");
            case 3:
                return str.replace(/(^\s*)/g, "");
            case 4:
                return str.replace(/(\s*$)/g, "");
            default:
                return str;
        }
    }
    
    /**
     * @param  {str} 
     * @param  {type}
     *       type:  1:       2:       3:       4:      5:    
     * @return {String}
     */
    changeCase (str, type) {
        type = type || 4
        switch (type) {
            case 1:
                return str.replace(/\b\w+\b/g, function (word) {
                    return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
    
                });
            case 2:
                return str.replace(/\b\w+\b/g, function (word) {
                    return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
                });
            case 3:
                return str.split('').map( function(word){
                    if (/[a-z]/.test(word)) {
                        return word.toUpperCase();
                    }else{
                        return word.toLowerCase()
                    }
                }).join('')
            case 4:
                return str.toUpperCase();
            case 5:
                return str.toLowerCase();
            default:
                return str;
        }
    }
    
    /*
              
    */
    checkPwd (str) {
        var Lv = 0;
        if (str.length < 6) {
            return Lv
        }
        if (/[0-9]/.test(str)) {
            Lv++
        }
        if (/[a-z]/.test(str)) {
            Lv++
        }
        if (/[A-Z]/.test(str)) {
            Lv++
        }
        if (/[\.|-|_]/.test(str)) {
            Lv++
        }
        return Lv;
    }
    
    /*  html  ( <>  )*/
    filterTag (str) {
        str = str.replace(/&/ig, "&");
        str = str.replace(//ig, ">");
        str = str.replace(" ", " ");
        return str;
    }