js常用方法パッケージ

9175 ワード


//     
function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length))
    }
  }
  return fmt
}

// type   0:      ,1:      ,2:      
function cTrim (sInputString, type) {
  var sTmpStr = ' ';
  var i = -1;

  if (type == 0 || type == 1) {
    while (sTmpStr == ' ') {
      ++i;
      sTmpStr = sInputString.substr(i, 1);
    }
    sInputString = sInputString.substring(i);
  }

  if (type == 0 || type == 2) {
    sTmpStr = ' ';
    i = sInputString.length;
    while (sTmpStr == ' ') {
      --i;
      sTmpStr = sInputString.substr(i, 1);
    }
    sInputString = sInputString.substring(0, i + 1);
  }
  return sInputString;
}

//url    
function getQueryString(name) {
  if (undefined == window.location) return null
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2].replace(/\%20/g, '+'))
  } else {
    return null
  }
}

//   cookie     
function getCookie(e) {
    var i = document.cookie.match(new RegExp('(^| )' + e + '=([^;]*)(;|$)'))
    if (i !== null) {
      return i[2]
    } else {
      return ''
    }
}

//   cookie     
function getCookie(name = '') {
  if (document.cookie.length > 0) {
    let start = document.cookie.indexOf(name + '=')
    if (start !== -1) {
      start = start + name.length + 1
      let end = document.cookie.indexOf(';', start)
      if (end === -1) end = document.cookie.length
      return unescape(document.cookie.substring(start, end))
    }
  }
  return null
}

//   cookie
function setCookie(name, value, expireHours) {
  let exDate = new Date()
  exDate.setTime(exDate.getTime() + expireHours * 60 * 60 * 1000)
  document.cookie = name + '=' + escape(value) + (typeof expireHours === 'undefined' ? '' : ';expires=' + exDate.toGMTString())
}

//   cookie
function delCookie(name = '') {
  let exDate = new Date()
  exDate.setTime(exDate.getTime() - 1)
  let value = getCookie(name)
  if (value !== null) {
    document.cookie = name + '=' + escape(value) + ';expires=' + exDate.toGMTString()
  }
}

//  、  、  、  sessionStorage(localStorage      )
function setSessionStorage(key, value) {
  sessionStorage.setItem(key, value)
}

function getSessionStorage(key) {
  return sessionStorage.getItem(key)
}

function delSessionStorage(key) {
  sessionStorage.removeItem(key) 
}

function clearSessionStorage() {
  sessionStorage.clear()
}

//     ,  ,ios,web
function getDeviceType() {
  var deviceType = 'WEB' //  
  var u = navigator.userAgent
  var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 
  var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) 
  if (isAndroid) {
    deviceType = 'ANDROID'
  } else if (isiOS) {
    deviceType = 'IOS'
  }
  return deviceType
}

//    ,   、  、  、   
let RegExp = {
  //      
  checkMobile(s) {
    var regu = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
    if (regu.test(s)) {
      return true
    } else {
      return false
    }
  },
  //              
  checkNomalName(s) {
    var regu = /^[\u4e00-\u9fa5]{2,}$/;
    if (regu.test(s)) {
      return true;
    } else {
      return false;
    }
  },
  //     
  isEmail(str) {
    var myReg = /^[-_A-Za-z0-9]+@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/;
    if (myReg.test(str)) return true;
    return false;
  },
  //        
  checkIdCard(idCard) {
    var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
    //       ,         ,        
    if (regIdCard.test(idCard)) {
      if (idCard.length == 18) {
        var idCardWi = new Array(7,  9,  10,  5,  8,  4,  2,  1,  6,  3,  7,  9,  10,  5,  8,  4,  2)  //  17           
        var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2) //    11 ,     11   、   ,      
        var idCardWiSum = 0 //     17             
        for (var i = 0; i < 17; i++) {
          idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i]
        }
        var idCardMod = idCardWiSum % 11 //             
        var idCardLast = idCard.substring(17) //           
        //    2,       10,            X
        if (idCardMod == 2) {
          if (idCardLast == 'X' || idCardLast == 'x') {
            return true
          } else {
            return false
          }
        } else {
          //                    ,    ,    ,           
          if (idCardLast == idCardY[idCardMod]) {
            return true
          } else {
            return false
          }
        }
      }
    } else {
      return false
    }
  }
}
//      
function arrayMax(arr) {
  return Math.max.apply(null, arr)
}
//      
function arrayMin(arr) {
  return Math.min.apply(null, arr)
}
//     
function arrayUnion(arr1, arr2) {
  return [...new Set([...arr1, ...arr2])]
}
//     
function arrayIntersect(arr1, arr2) {
  // let arr3 = [...arr1].filter(value => arr2.includes(value))
  // return [...new Set([...arr3])]
  return [...new Set([...arr1].filter(value => arr2.includes(value)))]
}
//     
function arrayDiff(arr1, arr2) {
  return [...new Set([...arr1].filter(value => !arr2.includes(value)))]
}
//     
function arrayUnique(arr) {
  return [...new Set([...arr])]
}
//localStorage  ,        
let handleLocalStorage = {
    //   localStorage,        
    setLocalStorageItem(key, value, exp) {
        var obj = new Object(),
            expires = exp.expires || null
        obj.value = value
        obj.time = new Date().getTime()
        // expires   
        if (expires === null) {
            delete obj.expires
        } else if (typeof expires === 'object') {
            obj.expires = expires.getTime() - obj.time
        } else if (typeof expires === 'number') {
            if ((expires | 0) !== expires) {
                throw new Error('expires must be integer number!')
            }
            // expires    365、366  ,   。       
            let days = new Date().getFullYear() % 4 === 0 ? 366 : 365
            if (expires <= days && expires > 0) {
                obj.expires = expires * 1000 * 60 * 60 * 24
            } else if (expires > days) {
                obj.expires = expires
            } else if (expires <= 0) {
                this.removeLocalStorageItem(key)
            }
        }
        localStorage.setItem(key, JSON.stringify(obj))
    },
    // getLocalStorageItem
    getLocalStorageItem(key) {
        var obj = JSON.parse(localStorage.getItem(key))
        if (obj === 'null' || obj === null) return null
        var expires = obj.expires,
            now = new Date().getTime(),
            time = obj.time

        if (now - time >= expires || now < time) {
            localStorage.removeItem(key)
            return null
        } else {
            return obj.value
        }
    },
    // removeLocalStorageItem
    removeLocalStorageItem(key) {
        if (this.getLocalStorageItem(key) !== null) {
            localStorage.removeItem(key)
            return this.getLocalStorageItem(key) === null ? true : false
        }
        return true
    },  
}
//   ,  ,       (address),      ,    ,    
let address = JSON.parse(handleLocalStorage. getLocalStorageItem('address'))
let limitTime = address.time + address.expires
let now =  new Date().getTime()
//     ,     
if (limitTime <= now) {
    handleLocalStorage.removeLocalStorageItem('address')
}
if(localStorage.address) {
    //      ,   localStorage    
} else {
   //     ,    
   //     ,             localStorage 
   handleLocalStorage.setLocalStorageItem('address', '   ' , {expires: 1})
}

//             ,      ,      ,         
window.scrollTo(10, 200)
//             ,      
function scrollTop(number = 0, time) {
    if (!time) {
        document.body.scrollTop = document.documentElement.scrollTop = number
        return number
     }
     const spacingTime = 20
     let spacingInex = time / spacingTime
     let nowTop = document.body.scrollTop + document.documentElement.scrollTop
     let everTop = (number - nowTop) / spacingInex
     let scrollTimer = setInterval(() => {
         if (spacingInex > 0) {
             spacingInex--
             scrollTop((nowTop += everTop))
         } else {
             clearInterval(scrollTimer)
         }
     }, spacingTime)
}
//   ,          
let ele = document.getElementById('scrollId')
this.scrollTop(ele.offsetTop, 200)