前端常用工具方法
1.邮箱
1 export const isEmail = (s) => { 2 return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s) 3 }
2.手机号码
1 export const isMobile = (s) => { 2 return /^1[0-9]{10}$/.test(s) 3 }
3.电话号码
1 export const isPhone = (s) => { 2 return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s) 3 }
4.是否url地址
1 export const isURL = (s) => { 2 return /^http[s]?:\/\/.*/.test(s) 3 }
5.是否字符串
1 export const isString = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'String' 3 }
6.是否数字
1 export const isNumber = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Number' 3 }
7.是否boolean
1 export const isBoolean = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean' 3 }
8.是否函数
1 export const isFunction = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Function' 3 }
9.是否为null
1 export const isNull = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Null' 3 }
10.是否undefined
1 export const isUndefined = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined' 3 }
11.是否对象
1 export const isObj = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Object' 3 }
12.是否数组
1 export const isArray = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Array' 3 }
13.是否时间
1 export const isDate = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Date' 3 }
14.是否正则
1 export const isRegExp = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'RegExp' 3 }
15.是否错误对象
1 export const isError = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Error' 3 }
16.是否Symbol函数
1 export const isSymbol = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Symbol' 3 }
17.是否Promise对象
1 export const isPromise = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Promise' 3 }
18.是否Set对象
1 export const isSet = (o) => { 2 return Object.prototype.toString.call(o).slice(8, -1) === 'Set' 3 }
1 export const ua = navigator.userAgent.toLowerCase();
19.是否是微信浏览器
1 export const isWeiXin = () => { 2 return ua.match(/microMessenger/i) == 'micromessenger' 3 }
20.是否是移动端
1 export const isDeviceMobile = () => { 2 return /android|webos|iphone|ipod|balckberry/i.test(ua) 3 }
21.是否是QQ浏览器
1 export const isQQBrowser = () => { 2 return !!ua.match(/mqqbrowser|qzone|qqbrowser|qbwebviewtype/i) 3 }
22.是否是爬虫
1 export const isSpider = () => { 2 return /adsbot|googlebot|bingbot|msnbot|yandexbot|baidubot|robot|careerbot|seznambot|bot|baiduspider|jikespider|symantecspider|scannerlwebcrawler|crawler|360spider|sosospider|sogou web sprider|sogou orion spider/.test(ua) 3 }
23.是否ios
1 export const isIos = () => { 2 var u = navigator.userAgent; 3 if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) { //安卓手机 4 return false 5 } else if (u.indexOf('iPhone') > -1) {//苹果手机 6 return true 7 } else if (u.indexOf('iPad') > -1) {//iPad 8 return false 9 } else if (u.indexOf('Windows Phone') > -1) {//winphone手机 10 return false 11 } else { 12 return false 13 } 14 }
24.是否为PC端
1 export const isPC = () => { 2 var userAgentInfo = navigator.userAgent; 3 var Agents = ["Android", "iPhone", 4 "SymbianOS", "Windows Phone", 5 "iPad", "iPod"]; 6 var flag = true; 7 for (var v = 0; v < Agents.length; v++) { 8 if (userAgentInfo.indexOf(Agents[v]) > 0) { 9 flag = false; 10 break; 11 } 12 } 13 return flag; 14 }
25.去除html标签
1 export const removeHtmltag = (str) => { 2 return str.replace(/<[^>]+>/g, '') 3 }
26.获取url参数
1 export const getQueryString = (name) => { 2 const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); 3 const search = window.location.search.split('?')[1] || ''; 4 const r = search.match(reg) || []; 5 return r[2]; 6 }
27.动态引入js
1 export const injectScript = (src) => { 2 const s = document.createElement('script'); 3 s.type = 'text/javascript'; 4 s.async = true; 5 s.src = src; 6 const t = document.getElementsByTagName('script')[0]; 7 t.parentNode.insertBefore(s, t); 8 }
28.根据url地址下载
1 export const download = (url) => { 2 var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; 3 var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1; 4 if (isChrome || isSafari) { 5 var link = document.createElement('a'); 6 link.href = url; 7 if (link.download !== undefined) { 8 var fileName = url.substring(url.lastIndexOf('/') + 1, url.length); 9 link.download = fileName; 10 } 11 if (document.createEvent) { 12 var e = document.createEvent('MouseEvents'); 13 e.initEvent('click', true, true); 14 link.dispatchEvent(e); 15 return true; 16 } 17 } 18 if (url.indexOf('?') === -1) { 19 url += '?download'; 20 } 21 window.open(url, '_self'); 22 return true; 23 }
29.el是否包含某个class
1 export const hasClass = (el, className) => { 2 let reg = new RegExp('(^|\\s)' + className + '(\\s|$)') 3 return reg.test(el.className) 4 }
30.el添加某个class
1 export const addClass = (el, className) => { 2 if (hasClass(el, className)) { 3 return 4 } 5 let newClass = el.className.split(' ') 6 newClass.push(className) 7 el.className = newClass.join(' ') 8 }
31.el去除某个class
1 export const removeClass = (el, className) => { 2 if (!hasClass(el, className)) { 3 return 4 } 5 let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g') 6 el.className = el.className.replace(reg, ' ') 7 }
32.获取滚动的坐标
1 export const getScrollPosition = (el = window) => ({ 2 x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, 3 y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop 4 });
33.滚动到顶部
1 export const scrollToTop = () => { 2 const c = document.documentElement.scrollTop || document.body.scrollTop; 3 if (c > 0) { 4 window.requestAnimationFrame(scrollToTop); 5 window.scrollTo(0, c - c / 8); 6 } 7 }
34.el是否在视口范围内
1 export const elementIsVisibleInViewport = (el, partiallyVisible = false) => { 2 const { top, left, bottom, right } = el.getBoundingClientRect(); 3 const { innerHeight, innerWidth } = window; 4 return partiallyVisible 5 ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && 6 ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) 7 : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; 8 }
35.洗牌算法随机
1 export const shuffle = (arr) => { 2 var result = [], 3 random; 4 while (arr.length > 0) { 5 random = Math.floor(Math.random() * arr.length); 6 result.push(arr[random]) 7 arr.splice(random, 1) 8 } 9 return result; 10 }
36.劫持粘贴板
1 export const copyTextToClipboard = (value) => { 2 var textArea = document.createElement("textarea"); 3 textArea.style.background = 'transparent'; 4 textArea.value = value; 5 document.body.appendChild(textArea); 6 textArea.select(); 7 try { 8 var successful = document.execCommand('copy'); 9 } catch (err) { 10 console.log('Oops, unable to copy'); 11 } 12 document.body.removeChild(textArea); 13 }
37.判断类型集合
1 export const checkStr = (str, type) => { 2 switch (type) { 3 case 'phone': //手机号码 4 return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str); 5 case 'tel': //座机 6 return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str); 7 case 'card': //身份证 8 return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str); 9 case 'pwd': //密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线 10 return /^[a-zA-Z]\w{5,17}$/.test(str) 11 case 'postal': //邮政编码 12 return /[1-9]\d{5}(?!\d)/.test(str); 13 case 'QQ': //QQ号 14 return /^[1-9][0-9]{4,9}$/.test(str); 15 case 'email': //邮箱 16 return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); 17 case 'money': //金额(小数点2位) 18 return /^\d*(?:\.\d{0,2})?$/.test(str); 19 case 'URL': //网址 20 return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str) 21 case 'IP': //IP 22 return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str); 23 case 'date': //日期时间 24 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) 25 case 'number': //数字 26 return /^[0-9]$/.test(str); 27 case 'english': //英文 28 return /^[a-zA-Z]+$/.test(str); 29 case 'chinese': //中文 30 return /^[\\u4E00-\\u9FA5]+$/.test(str); 31 case 'lower': //小写 32 return /^[a-z]+$/.test(str); 33 case 'upper': //大写 34 return /^[A-Z]+$/.test(str); 35 case 'HTML': //HTML标记 36 return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str); 37 default: 38 return true; 39 } 40 }
38.严格的身份证校验
1 export const isCardID = (sId) => { 2 if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) { 3 console.log('你输入的身份证长度或格式错误') 4 return false 5 } 6 //身份证城市 7 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: "国外" }; 8 if (!aCity[parseInt(sId.substr(0, 2))]) { 9 console.log('你的身份证地区非法') 10 return false 11 } 12 13 // 出生日期验证 14 var sBirthday = (sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2))).replace(/-/g, "/"), 15 d = new Date(sBirthday) 16 if (sBirthday != (d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate())) { 17 console.log('身份证上的出生日期非法') 18 return false 19 } 20 21 // 身份证号码校验 22 var sum = 0, 23 weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], 24 codes = "10X98765432" 25 for (var i = 0; i < sId.length - 1; i++) { 26 sum += sId[i] * weights[i]; 27 } 28 var last = codes[sum % 11]; //计算出来的最后一位身份证号码 29 if (sId[sId.length - 1] != last) { 30 console.log('你输入的身份证号非法') 31 return false 32 } 33 34 return true 35 }
39.随机数范围
1 export const random = (min, max) => { 2 if (arguments.length === 2) { 3 return Math.floor(min + Math.random() * ((max + 1) - min)) 4 } else { 5 return null; 6 } 7 }
40.将阿拉伯数字翻译成中文的大写数字