JS常用转换方法收集,持续更新
一,时间、数字、字符串部分
日期格式化
/**
* 日期格式化
* @param {*} date 时间
* @param {String} format 时间格式,默认YYYY-MM-DD hh:mm:ss
*/
export const dateFormat = (date = new Date(), format = 'YYYY-MM-DD hh:mm:ss') => {
if (typeof date != 'object') date = new Date(date)
const munFix = (n) => n < 10 ? ('0' + n) : n
return format
.replace('YYYY', date.getFullYear())
.replace('MM', munFix(date.getMonth() + 1))
.replace('DD', munFix(date.getDate()))
.replace('hh', munFix(date.getHours()))
.replace('mm', munFix(date.getMinutes()))
.replace('ss', munFix(date.getSeconds()))
}
秒数转换成分钟
export const formatPlayTime = time => {
let m = parseInt(time / 60)
let s = parseInt(time % 60)
return m === 0 && s === 0 ? '--/--' : (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s)
}
export const formatPlayTime2 = time => {
let m = parseInt(time / 60)
let s = parseInt(time % 60)
return (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s)
}
获取两个数之间的随机整数,大于等于min,小于max
export const getRandom = (min, max) => Math.floor(Math.random() * (max - min)) + min
文件大小转换
export const sizeFormate = size => {
// https://gist.github.com/thomseddon/3511330
if (!size) return '0 B'
let units = ['B', 'KB', 'MB', 'GB', 'TB']
let number = Math.floor(Math.log(size) / Math.log(1024))
return `${(size / Math.pow(1024, Math.floor(number))).toFixed(2)} ${units[number]}`
}
首字母大小
export function titleCase(str) {
return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}
下划转驼峰
export function camelCase(str) {
return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}
判断是否是数字型字符串
export function isNumberStr(str) {
return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}
二,请求与编码部分
字符串解码
const encodeNames = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'",
''': "'",
}
export const decodeName = (str = '') => str?.replace(/(?:&|<|>|"|'|')/gm, s => encodeNames[s]) || ''
解析URL参数为对象
// 解析URL参数为对象
export const parseUrlParams = str => {
const params = {}
if (typeof str !== 'string') return params
const paramsArr = str.split('&')
for (const param of paramsArr) {
let [key, value] = param.split('=')
params[key] = value
}
return params
}
三,常用方法
防抖节流
/**
* 生成节流函数
* @param {*} fn
* @param {*} delay
*/
export const throttle = (fn, delay = 100) => {
let timer = null
let _args = null
return function(...args) {
_args = args
if (timer) return
timer = setTimeout(() => {
timer = null
fn.apply(this, _args)
}, delay)
}
}
/**
* 生成防抖函数
* @param {*} fn
* @param {*} delay
*/
export const debounce = (fn, delay = 100) => {
let timer = null
let _args = null
return function(...args) {
_args = args
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
timer = null
fn.apply(this, _args)
}, delay)
}
}