![37c61e768a99f015c2ac785e94fcab06.png](https://i-blog.csdnimg.cn/blog_migrate/055590eebf60cfca50b0ef3c62c6b5d0.jpeg)
前言
本文总结了项目开发过程中常用的js函数和正则,意在提高大家平时的开发效率,具体内容如下:
- 常用的正则校验
- 常用的设备检测方式
- 常用的日期时间函数
- 跨端事件处理
- js移动端适配方案
- xss预防方式
- 常用的js算法(防抖,截流,去重,排序,模板渲染,观察者...)
代码
- 正则
// 匹配邮箱let reg = /^([a-zA-Z]|[0-9])(w|-)+@[a-zA-Z0-9]+.([a-zA-Z]{2,4})$// (新)匹配手机号let reg = /^1[0-9]{10}$/;// (旧)匹配手机号let reg = /^1(3|4|5|7|8)[0-9]{9}$/;// 匹配8-16位数字和字母密码的正则表达式let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/;// 匹配国内电话号码 0510-4305211let reg = /d{3}-d{8}|d{4}-d{7}/;// 匹配身份证号码let reg=/(^d{15}$)|(^d{18}$)|(^d{17}(d|X|x)$)/;// 匹配腾讯QQ号let reg = /[1-9][0-9]{4,}/;// 匹配ip地址let reg = /d+.d+.d+.d+/;// 匹配中文let reg = /^[一-龥]*$/;
- 检测平台(设备)类型
let isWechat = /micromessenger/i.test(navigator.userAgent), isWeibo = /weibo/i.test(navigator.userAgent), isQQ = /qq//i.test(navigator.userAgent), isIOS = /(iphone|ipod|ipad|ios)/i.test(navigator.userAgent), isAndroid = /android/i.test(navigator.userAgent);
- 常用的日期时间函数
// 时间格式化function format_date(timeStamp) { let date = new Date(timeStamp); return date.getFullYear() + "年" + prefix_zero(date.getMonth() + 1) + "月" + prefix_zero(date.getDate()) + "日 " + prefix_zero(date.getHours()) + ":" + prefix_zero(date.getMinutes());}// 数字格式化function prefix_zero(num) { return num >= 10 ? num : "0" + num;}// 倒计时时间格式化function format_time(timeStamp) { let day = Math.floor(timeStamp / (24 * 3600 * 1000)); let leave1 = timeStamp % (24 * 3600 * 1000); let hours = Math.floor(leave1 / (3600 * 1000)); let leave2 = leave1 % (3600 * 1000); let minutes = Math.floor(leave2 / (60 * 1000)); let leave3 = leave2 % (60 * 1000); let seconds = Math.floor(leave3 / 1000); if (day) return day + "天" + hours + "小时" + minutes + "分"; if (hours) return hours + "小时" + minutes + "分" + seconds + "秒"; if (minutes) return minutes + "分" + seconds + "秒"; if (seconds) return seconds + "秒"; return "时间到!";}
- 跨端事件处理
// 是否支持触摸事件let isSupportTouch = ("ontouchstart" in document.documentElement) ? true : false;//禁用Enter键表单自动提交document.onkeydown = function(event) { let target, code, tag; if (!event) { event = window.event; //针对ie浏览器 target = event.srcElement; code = event.keyCode; if (code == 13) { tag = target.tagName; if (tag == "TEXTAREA") { return true; } else { return false; } } } else { target = event.target; //针对遵循w3c标准的浏览器,如Firefox code = event.keyCode; if (code == 13) { tag = target.tagName; if (tag == "INPUT") { return false; } else { return true; } } }};
- 移动端适配方案
(function (doc, win) { var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function () { var clientWidth = docEl.clientWidth; var fontSize = 20; docEl.style.fontSize = fontSize + 'px'; var docStyles = getComputedStyle(docEl); var realFontSize = parseFloat(docStyles.fontSize); var scale = realFontSize / fontSize; console.log("realFontSize: " + realFontSize +