本文已参与[新人创作礼]活动,一起开启掘金创作之路
今日分享一篇积累和收集了很久的JS utils工具函数,文章代码量较多,建议收藏起来慢慢看,当哪一天需要用到的时候,打开你尘封已久的收藏夹,相信能让你的业务代码开发事半功倍。
汇集了时间相关,DOM相关,URL相关,判断相关,图片相关,缓存相关等。部分逻辑处理较为简单,如果是业务量较为复杂的情况建议要斟酌使用,但对于大部分的项目应该是绰绰有余。接下来就进入代码部分吧~
时间相关
时间戳转自定义格式时间
export const dateRegExp = (time, strText) => { const date = new Date(time) if (/(y+)/.test(strText)) { strText = strText.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) } const dataType = { 'M+': date.getMonth() + 1, 'd+': date.getDate(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds() } for (const typeKey in dataType) { if (new RegExp(`(${typeKey})`).test(strText)) { const typeValue = dataType[typeKey] + '' strText = strText.replace(RegExp.$1, (RegExp.$1.length === 1 ? typeValue : padLeftZero(typeValue))) } } return strText }
格式化距离现在已过去的时间
export function formatPassTime(startTime) { var currentTime = Date.parse(new Date()), time = currentTime - startTime, day = parseInt(time / (1000 * 60 * 60 * 24)), hour = parseInt(time / (1000 * 60 * 60)), min = parseInt(time / (1000 * 60)), month = parseInt(day / 30), year = parseInt(month / 12); if (year) return year + "年前" if (month) return month + "个月前" if (day) return day + "天前" if (hour) return hour + "小时前" if (min) return min + "分钟前" else return '刚刚' }
判断两个不同格式的日期是否为同一天
export function isSameDay(d1, d2) { if (!d2) { d2 = new Date(); } var d1_year = d1.getFullYear(), d1_month = d1.getMonth() + 1, d1_date = d1.getDate(); var d2_year = d2.getFullYear(), d2_month = d2.getMonth() + 1, d2_date = d2.getDate() return d1_date === d2_date && d1_month === d2_month && d1_year === d2_year; }
判断时间是不是今天
export function isTodayDate(time) { if (new Date(time).toDateString() === new Date().toDateString()) { return true; } return false; }
URL 相关
URL 参数转对象
export function parseQueryString(url) { url = url ? url:window.location.search ; let search = url[0] === '?' ? url : url.substring(url.lastIndexOf('?')); let q = {}; search.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => q[k] = decodeURIComponent(v)); return q; }
获取URL参数
export function getQueryString(name) { const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i') const r = window.location.search.substr(1).match(reg) if (r !== null) { return decodeURI(r[2]) } return null }
获取URL hash后面的参数
export getHashQueryString = (key) => { const after = window.location.href.split('?')[1] if (after) { const reg = new RegExp(`(^|&)${ key }=([^&]*)(&|$)`) const r = after.match(reg) if (r != null) { return decodeURIComponent(r[2]) } return null } return null }
对象序列化
export function serialize(query, encode = false) { return Object.keys(query) .map((key) => `${key}=${encode ? encodeURIComponent(query[key]) : query[key]}`) .join('&') }
判断相关
判断是否支持 Intersection
export function isSupportIntersection() { return ( 'IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype ) }
判断是否IOS
export const isIOS = (() => { return /ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()) })()
判断是否安卓
export const isAndroid = (() { return /android/.test(navigator.userAgent.toLowerCase()) })()
判断微信内置浏览器
export function isWeixin() { var ua = navigator.userAgent.toLowerCase(); return (ua.match(/MicroMessenger/i) == "micromessenger") }
判断是否支持webp格式 2种方式
export function checkSupportWebp() { return ( document .createElement('canvas') .toDataURL('image/webp') .indexOf('data:image/webp') === 0 ) } export function checkSupportWebp2() { var img = new Image(); img.onload = img.onerror = (event) => { return event && event.type === "load" ? img.width == 1 : false; }; img.src = "data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA="; }
判断浏览器是否是移动端
export function isMobile() { const agent = navigator.userAgent; const k = ["android", "iphone", "ipod", "ipad", "windows phone", "mqqbrowser"]; let flag = false; // Windows if (agent.indexOf("Windows NT") < 0 || (agent.indexOf("Windows NT") >= 0 && agent.indexOf("compatible; MSIE 9.0;") >= 0)) { // Mac PC if (agent.indexOf("Windows NT") < 0 && agent.indexOf("Macintosh") < 0) { for (let item of k) { if (agent.indexOf(item) >= 0) { flag = true; break; } } } } return flag; }
文件类型判断
export function checkFileName(fileName, list) { if (typeof fileName !== 'string') return; let name = fileName.toLowerCase(); return list.some(i => name.endsWith(`.${i}`) === true) } export function isImage(fileName) { return checkFileName(fileName, ['png', 'jpeg', 'jpg', 'png', 'bmp']) } export function isH5Video(fileName) { return checkFileName(fileName, ['mp4', 'webm', 'ogg']) } export function isPdf(fileName) { return checkFileName(fileName, ['pdf']) } export function isWord(fileName) { return checkFileName(fileName, ['doc', 'docx']) } export function isExcel(fileName) { return checkFileName(fileName, ['xlsx', 'xls']) }
数据类型判断
export function is(subject, type) { return Object.prototype.toString.call(subject).substr(8, type.length).toLowerCase() === type } export function isArray(subject) { return Array.isArray(subject) } export function isObject(subject) { return is(subject, 'object') } ... export function isNum(subject) { return !isNaN(subject) && is(subject, 'number') }