javascript通用的方法封装总结

总结一些好用的方法,以后直接拿来用,省时省力,后续想起来更新会继续补充

1. 时间戳或Date对象转换为易读格式

function parseTime(time, cFormat) {
    if (arguments.length == 0) return
    cFormat = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date = null
    if (typeof time == 'objec') {
        date = time
    } else {
        if ((time + '').length == 10) time = parseInt(time) * 1000
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const timeStr = cFormat.replace(/{(y|m|d|h|i|s|a)+}/g,(res,key) => {
        let val = formatObj[key]
        if (key === 'a') return ['一','二','三','四','五','六','日'][val - 1]
        if (res.length > 0 && val < 10) {
            val = '0' + val
        }
        return val || 0
    })
    return timeStr
}
let now = new Date()
let nowTime = new Date().getTime()
console.log(parseTime(now)) // 2023=12-15 12:20:20
console.log(parseTime(nowTime)) // 2023=12-15 12:20:20

2. 获取某年某月有多少天

function getDaysInMonth(year,month) {
    return new Date(year,parseInt(month),0).getDate()
}
console.log(getDaysInMonth(2023,12)) // 31

3. 数字金额转换为中文

function numberToChinese(money) {
    const charArr = ['零','一','二','三','四','五','六','七','八','九']
    const charUnitArr = ['','十','百','千','万','十','百','千','亿','十','百','千','万']
    let [str, strUnit] = ['', '']
    let unitPos = 0
    let zero = true
    while (money > 0) {
        let v = money % 10
        if (v === 0) {
            if (!zero) {
                zero = true
                strUnit = charArr[v] + strUnit
            }
        } else {
            zero = false
            str = charArr[v]
            str += charUnitArr[unitPos]
            strUnit = str + strUnit
        }
        unitPos++
        money = Math.floor(money / 10)
    }
    // strUnit += strUnit.charAt(strUnit.length - 1) == '元' ? '整' : ''
    return strUnit
}
console.log(numberToChinese(2222222222312)) // 二万二千二百二十二亿二千二百二十二万二千三百一十二

4. 数字金额小写转换为大写

function numberToChinese(money) {
    const chineseChar = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖']
    const unitArr = ['万','仟','佰','拾','','仟','佰','拾','','仟','佰','拾','','角','分']
    money = Math.round(money)
    let minus = ''
    if (money < 0) {
        money = Math.abs(money)
        minus = '负'
    }
    money += ''
    let length = money.length
    let result = ''
    for (let i = 0; i < length; i++ ) {
        // debugger
        if (i == 2) {
            result = '元' + result
        } else if (i == 6) {
            result = '万' + result
        } else if (i == 10) {
            if (result.charAt(0) == '万') {
                result = result.substr(1)
                if (result && result.charAt(0) != '零' 
                    && result.charAt(0) != '元' 
                    && result.charAt(0) != '拾' 
                    && result.charAt(0) != '佰' 
                    && result.charAt(0) != '仟' 
                    && result.charAt(0) != '万'
                    && result.charAt(0) != '亿') {
                    result = '零' + result
                }
            }
            
            result = '亿' + result
        }
        if (money.charAt(length - i - 1) == 0) {
            if (i != 0 && i != 1) {
                if (result && result.charAt(0) != '零' 
                    && result.charAt(0) != '元' 
                    && result.charAt(0) != '拾' 
                    && result.charAt(0) != '佰' 
                    && result.charAt(0) != '仟' 
                    && result.charAt(0) != '万'
                    && result.charAt(0) != '亿') {
                    result = '零' + result
                }
            }
            if (i == 1 && result) {
                result = '零' + result
            }
            continue
        }
        result = chineseChar[parseInt(money.charAt(length - i - 1))] + unitArr[unitArr.length - i - 1] + result
    }
    result += result.charAt(result.length - 1) == '元' ? '整' : ''
    return minus + result
}
console.log(numberToChinese(900200289679)) // 玖拾亿零贰佰万贰仟捌佰玖拾陆元柒角玖分
console.log(numberToChinese(900000000000)) // 玖拾亿元整

5. 校验URL是否合法

function validateURL(textval) {
    const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
    return urlregex.test(textval)
}
console.log(validateURL('https://www.baidu.com')) // true
console.log(validateURL('https://www.123')) // false

6. 校验邮件是否合法

function validateEmail(email) {
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return re.test(email)
}
console.log(validateEmail('0000000@qq.com')) // true
console.log(validateEmail('cscss@@163.com')) // false

7. 校验手机号是否正确

function validatePhone(phone) {
    const re = /^1[3456789]\d{9}$/
    return re.test(phone)
}
console.log(validatePhone('18790886988')) // true
console.log(validatePhone('1879071698')) // false

8. 校验是否全是汉字

function validateChinese(str) {
    const re = /^[\u4e00-\u9fa5]*$/g
    return re.test(str)
}
console.log(validateChinese('你怎么那么帅啊')) // true
console.log(validateChinese('你怎么那么帅a')) // false

9. 校验身份证号码是否合法

function validateID(num) {
    num = num + ''
    num = num.toUpperCase()
    if (!(/(^\d{17}([0-9]|X)$)/.test(num))) {
        return false
    }

    const len = num.length
    if (len === 18) {
        const re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/)
        const arrSplit = num.match(re)

        // 检查生日日期是否正确
        const dtmBirth = new Date(arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
        const bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]))

        if (!bGoodDay) {
            console.log('请检查输入身份证出生日期')
            return false
        } else {
            // 检验18位身份证的校验码是否正确。
            // 校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
            let valnum = 0
            const arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
            const arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
            let nTemp = 0
            for (let i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i]
            }
            valnum = arrCh[nTemp % 11]

            if (valnum !== num.substr(17, 1)) {
                console.log('请输入有效的身份证号')
                return false
            } else {
                return true
            }
        }
    }

    return true
}
//这个就不举例了

10. 判空

function validateIsNull(val) {
    if ((typeof val == 'string' && val.trim() == '') || val == undefined || val == null || isNaN(val) || isFinite(val)) {
        return true
    }
    
    if (val.constructor === Array || val.constructor === Object) {
        let newVal = JSON.stringify(val)
        if (newVal == '{}' || newVal == '[]') {
            return true
        }
    }
    return false
}
console.log(validateIsNull([]))// true
console.log(validateIsNull({}))// true
console.log(validateIsNull(null))// true
console.log(validateIsNull(undefined))// true
console.log(validateIsNull(NaN))// true
console.log(validateIsNull('  '))// true

11. 获取URL携带参数serarch

function urlQuery (uri) {
  uri = !uri ? window.location : uri
  var url = typeof uri === 'object' ? uri.href : uri
  var uriQuery = uri.search
  if (url.indexOf('?') < 0 || (!uriQuery && typeof uriQuery !== 'function')) {
    return ''
  }
  uriQuery = typeof uriQuery === 'function' ? url.match(/(.*?)\?(.*)/)[2] : uriQuery.match(/^\?(.*)/)[1]
  uriQuery = uriQuery.indexOf('#') > -1 ? uriQuery.match(/(.*?)#(.*)/)[1] : uriQuery
  return uriQuery
}
console.log(urlQuery('https://xxx.com/?to=index&toLogin=mobileLogin'))// to=index&toLogin=mobileLogin

12. 获取URL参数组装成JSON

function getAllParams (url) {
  url = url || window.location.href
  let s = urlQuery(url) || '', map = {}
  s.replace(/([^&]*?)\=(.*?)(&|$)/ig, function (a, key, value) {
    map[key] = value
  })
  return map
}
console.log(getAllParams('https://xxx.com/?to=index&toLogin=mobileLogin'))// {to: 'index',toLogin: 'mobileLogin'}

13. 解析JSON为URL,设置URL参数

//解析JSON为URL
function serializer (json) {
  json = json || {}
  var str = []
  for (var key in json) {
    !!json[key] && str.push(key + '=' + json[key])
  }
  return str.join('&')
}
console.log(serializer({time: 1703039843750,status: 1})) // time=1703039843750&status=1

//设置URL参数
function setParams (params, url) {
  params = params || {}
  url = url || window.location.href
  var oriParams = getAllParams(url)
  var query
  for (var key in params) {
    if (params[key]) {
      oriParams[key] = params[key]
    }
  }
  query = serializer(oriParams)
  return  url.indexOf('?') > -1 ? (url.split('?')[0] + '?' + query) : (url + '?' + query)
}
console.log(setParams({time: 1703039843750,status: 1},'https://xxx.com/')) // https://xxx.com/?time=1703039843750&status=1

14. 获取 url 参数值

function queryParam (key, url) {
  url = url || window.location.href
  var reg = new RegExp('[?&#]' + key + '=([^&#]*)', 'i'),
    match = url.match(reg)
  if (match) {
    try {
      return decodeURIComponent(match[1]) || ''
    } catch (e) {

    }
  }
  return ''
}
console.log(queryParam('toLogin','https://xxx.com/?to=index&toLogin=mobileLogin'))// mobileLogin
  • 15
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值