码迷,mamicode.com
首页 > 其他好文 > 详细

前端常用工具方法

时间:2020-06-07 19:24:09      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:define   翻译   新疆   dex   iphone   ops   err   fse   之间   

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.将阿拉伯数字翻译成中文的大写数字

 1 export const numberToChinese = (num) => {
 2     var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
 3     var BB = new Array("", "十", "百", "仟", "萬", "億", "点", "");
 4     var a = ("" + num).replace(/(^0*)/g, "").split("."),
 5         k = 0,
 6         re = "";
 7     for (var i = a[0].length - 1; i >= 0; i--) {
 8         switch (k) {
 9             case 0:
10                 re = BB[7] + re;
11                 break;
12             case 4:
13                 if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$")
14                     .test(a[0]))
15                     re = BB[4] + re;
16                 break;
17             case 8:
18                 re = BB[5] + re;
19                 BB[7] = BB[5];
20                 k = 0;
21                 break;
22         }
23         if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
24             re = AA[0] + re;
25         if (a[0].charAt(i) != 0)
26             re = AA[a[0].charAt(i)] + BB[k % 4] + re;
27         k++;
28     }
29 
30     if (a.length > 1) // 加上小数部分(如果有小数部分)
31     {
32         re += BB[6];
33         for (var i = 0; i < a[1].length; i++)
34             re += AA[a[1].charAt(i)];
35     }
36     if (re == ‘一十‘)
37         re = "十";
38     if (re.match(/^一/) && re.length == 3)
39         re = re.replace("一", "");
40     return re;
41 }

41.将数字转换为大写金额

  1 export const changeToChinese = (Num) => {
  2     //判断如果传递进来的不是字符的话转换为字符
  3     if (typeof Num == "number") {
  4         Num = new String(Num);
  5     };
  6     Num = Num.replace(/,/g, "") //替换tomoney()中的“,”
  7     Num = Num.replace(/ /g, "") //替换tomoney()中的空格
  8     Num = Num.replace(/¥/g, "") //替换掉可能出现的¥字符
  9     if (isNaN(Num)) { //验证输入的字符是否为数字
 10         //alert("请检查小写金额是否正确");
 11         return "";
 12     };
 13     //字符处理完毕后开始转换,采用前后两部分分别转换
 14     var part = String(Num).split(".");
 15     var newchar = "";
 16     //小数点前进行转化
 17     for (var i = part[0].length - 1; i >= 0; i--) {
 18         if (part[0].length > 10) {
 19             return "";
 20             //若数量超过拾亿单位,提示
 21         }
 22         var tmpnewchar = ""
 23         var perchar = part[0].charAt(i);
 24         switch (perchar) {
 25             case "0":
 26                 tmpnewchar = "零" + tmpnewchar;
 27                 break;
 28             case "1":
 29                 tmpnewchar = "壹" + tmpnewchar;
 30                 break;
 31             case "2":
 32                 tmpnewchar = "贰" + tmpnewchar;
 33                 break;
 34             case "3":
 35                 tmpnewchar = "叁" + tmpnewchar;
 36                 break;
 37             case "4":
 38                 tmpnewchar = "肆" + tmpnewchar;
 39                 break;
 40             case "5":
 41                 tmpnewchar = "伍" + tmpnewchar;
 42                 break;
 43             case "6":
 44                 tmpnewchar = "陆" + tmpnewchar;
 45                 break;
 46             case "7":
 47                 tmpnewchar = "柒" + tmpnewchar;
 48                 break;
 49             case "8":
 50                 tmpnewchar = "捌" + tmpnewchar;
 51                 break;
 52             case "9":
 53                 tmpnewchar = "玖" + tmpnewchar;
 54                 break;
 55         }
 56         switch (part[0].length - i - 1) {
 57             case 0:
 58                 tmpnewchar = tmpnewchar + "元";
 59                 break;
 60             case 1:
 61                 if (perchar != 0) tmpnewchar = tmpnewchar + "拾";
 62                 break;
 63             case 2:
 64                 if (perchar != 0) tmpnewchar = tmpnewchar + "佰";
 65                 break;
 66             case 3:
 67                 if (perchar != 0) tmpnewchar = tmpnewchar + "仟";
 68                 break;
 69             case 4:
 70                 tmpnewchar = tmpnewchar + "万";
 71                 break;
 72             case 5:
 73                 if (perchar != 0) tmpnewchar = tmpnewchar + "拾";
 74                 break;
 75             case 6:
 76                 if (perchar != 0) tmpnewchar = tmpnewchar + "佰";
 77                 break;
 78             case 7:
 79                 if (perchar != 0) tmpnewchar = tmpnewchar + "仟";
 80                 break;
 81             case 8:
 82                 tmpnewchar = tmpnewchar + "亿";
 83                 break;
 84             case 9:
 85                 tmpnewchar = tmpnewchar + "拾";
 86                 break;
 87         }
 88         var newchar = tmpnewchar + newchar;
 89     }
 90     //小数点之后进行转化
 91     if (Num.indexOf(".") != -1) {
 92         if (part[1].length > 2) {
 93             // alert("小数点之后只能保留两位,系统将自动截断");
 94             part[1] = part[1].substr(0, 2)
 95         }
 96         for (i = 0; i < part[1].length; i++) {
 97             tmpnewchar = ""
 98             perchar = part[1].charAt(i)
 99             switch (perchar) {
100                 case "0":
101                     tmpnewchar = "零" + tmpnewchar;
102                     break;
103                 case "1":
104                     tmpnewchar = "壹" + tmpnewchar;
105                     break;
106                 case "2":
107                     tmpnewchar = "贰" + tmpnewchar;
108                     break;
109                 case "3":
110                     tmpnewchar = "叁" + tmpnewchar;
111                     break;
112                 case "4":
113                     tmpnewchar = "肆" + tmpnewchar;
114                     break;
115                 case "5":
116                     tmpnewchar = "伍" + tmpnewchar;
117                     break;
118                 case "6":
119                     tmpnewchar = "陆" + tmpnewchar;
120                     break;
121                 case "7":
122                     tmpnewchar = "柒" + tmpnewchar;
123                     break;
124                 case "8":
125                     tmpnewchar = "捌" + tmpnewchar;
126                     break;
127                 case "9":
128                     tmpnewchar = "玖" + tmpnewchar;
129                     break;
130             }
131             if (i == 0) tmpnewchar = tmpnewchar + "角";
132             if (i == 1) tmpnewchar = tmpnewchar + "分";
133             newchar = newchar + tmpnewchar;
134         }
135     }
136     //替换所有无用汉字
137     while (newchar.search("零零") != -1)
138         newchar = newchar.replace("零零", "零");
139     newchar = newchar.replace("零亿", "亿");
140     newchar = newchar.replace("亿万", "亿");
141     newchar = newchar.replace("零万", "万");
142     newchar = newchar.replace("零元", "元");
143     newchar = newchar.replace("零角", "");
144     newchar = newchar.replace("零分", "");
145     if (newchar.charAt(newchar.length - 1) == "元") {
146         newchar = newchar + "整"
147     }
148     return newchar;
149 }

42.判断一个元素是否在数组中

1 export const contains = (arr, val) => {
2     return arr.indexOf(val) != -1 ? true : false;
3 }

43.数组排序,{type} 1:从小到大 2:从大到小 3:随机

 1 export const sort = (arr, type = 1) => {
 2     return arr.sort((a, b) => {
 3         switch (type) {
 4             case 1:
 5                 return a - b;
 6             case 2:
 7                 return b - a;
 8             case 3:
 9                 return Math.random() - 0.5;
10             default:
11                 return arr;
12         }
13     })
14 }

44.去重

 1 export const unique = (arr) => {
 2     if (Array.hasOwnProperty(‘from‘)) {
 3         return Array.from(new Set(arr));
 4     } else {
 5         var n = {}, r = [];
 6         for (var i = 0; i < arr.length; i++) {
 7             if (!n[arr[i]]) {
 8                 n[arr[i]] = true;
 9                 r.push(arr[i]);
10             }
11         }
12         return r;
13     }
14 }

45.求两个集合的并集

1 export const union = (a, b) => {
2     var newArr = a.concat(b);
3     return this.unique(newArr);
4 }

46.求两个集合的交集

1 export const intersect = (a, b) => {
2     var _this = this;
3     a = this.unique(a);
4     return this.map(a, function (o) {
5         return _this.contains(b, o) ? o : null;
6     });
7 }

47.删除其中一个元素

1 export const remove = (arr, ele) => {
2     var index = arr.indexOf(ele);
3     if (index > -1) {
4         arr.splice(index, 1);
5     }
6     return arr;
7 }

48.将类数组转换为数组

1 export const formArray = (ary) => {
2     var arr = [];
3     if (Array.isArray(ary)) {
4         arr = ary;
5     } else {
6         arr = Array.prototype.slice.call(ary);
7     };
8     return arr;
9 }

49.最大值

1 export const max = (arr) => {
2     return Math.max.apply(null, arr);
3 }

50.最小值

1 export const min = (arr) => {
2     return Math.min.apply(null, arr);
3 }

51.求和

1 export const sum = (arr) => {
2     return arr.reduce((pre, cur) => {
3         return pre + cur
4     })
5 }

52.平均值

1 export const average = (arr) => {
2     return this.sum(arr) / arr.length
3 }

53.去除空格,type: 1-所有空格 2-前后空格 3-前空格 4-后空格

 1 export const trim = (str, type) => {
 2     type = type || 1
 3     switch (type) {
 4         case 1:
 5             return str.replace(/\s+/g, "");
 6         case 2:
 7             return str.replace(/(^\s*)|(\s*$)/g, "");
 8         case 3:
 9             return str.replace(/(^\s*)/g, "");
10         case 4:
11             return str.replace(/(\s*$)/g, "");
12         default:
13             return str;
14     }
15 }

54.字符转换,type: 1:首字母大写 2:首字母小写 3:大小写转换 4:全部大写 5:全部小写

 1 export const changeCase = (str, type) => {
 2     type = type || 4
 3     switch (type) {
 4         case 1:
 5             return str.replace(/\b\w+\b/g, function (word) {
 6                 return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
 7 
 8             });
 9         case 2:
10             return str.replace(/\b\w+\b/g, function (word) {
11                 return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
12             });
13         case 3:
14             return str.split(‘‘).map(function (word) {
15                 if (/[a-z]/.test(word)) {
16                     return word.toUpperCase();
17                 } else {
18                     return word.toLowerCase()
19                 }
20             }).join(‘‘)
21         case 4:
22             return str.toUpperCase();
23         case 5:
24             return str.toLowerCase();
25         default:
26             return str;
27     }
28 }

55.检测密码强度

 1 export const checkPwd = (str) => {
 2     var Lv = 0;
 3     if (str.length < 6) {
 4         return Lv
 5     }
 6     if (/[0-9]/.test(str)) {
 7         Lv++
 8     }
 9     if (/[a-z]/.test(str)) {
10         Lv++
11     }
12     if (/[A-Z]/.test(str)) {
13         Lv++
14     }
15     if (/[\.|-|_]/.test(str)) {
16         Lv++
17     }
18     return Lv;
19 }

56.函数节流器

1 export const debouncer = (fn, time, interval = 200) => {
2     if (time - (window.debounceTimestamp || 0) > interval) {
3         fn && fn();
4         window.debounceTimestamp = time;
5     }
6 }

57.在字符串中插入新字符串

1 export const insertStr = (soure, index, newStr) => {
2     var str = soure.slice(0, index) + newStr + soure.slice(index);
3     return str;
4 }

58.判断两个对象是否键值相同

 1 export const isObjectEqual = (a, b) => {
 2     var aProps = Object.getOwnPropertyNames(a);
 3     var bProps = Object.getOwnPropertyNames(b);
 4 
 5     if (aProps.length !== bProps.length) {
 6         return false;
 7     }
 8 
 9     for (var i = 0; i < aProps.length; i++) {
10         var propName = aProps[i];
11 
12         if (a[propName] !== b[propName]) {
13             return false;
14         }
15     }
16     return true;
17 }

59.16进制颜色转RGBRGBA字符串

 1 export const colorToRGB = (val, opa) => {
 2 
 3     var pattern = /^(#?)[a-fA-F0-9]{6}$/; //16进制颜色值校验规则
 4     var isOpa = typeof opa == ‘number‘; //判断是否有设置不透明度
 5 
 6     if (!pattern.test(val)) { //如果值不符合规则返回空字符
 7         return ‘‘;
 8     }
 9 
10     var v = val.replace(/#/, ‘‘); //如果有#号先去除#号
11     var rgbArr = [];
12     var rgbStr = ‘‘;
13 
14     for (var i = 0; i < 3; i++) {
15         var item = v.substring(i * 2, i * 2 + 2);
16         var num = parseInt(item, 16);
17         rgbArr.push(num);
18     }
19 
20     rgbStr = rgbArr.join();
21     rgbStr = ‘rgb‘ + (isOpa ? ‘a‘ : ‘‘) + ‘(‘ + rgbStr + (isOpa ? ‘,‘ + opa : ‘‘) + ‘)‘;
22     return rgbStr;
23 }

60.追加url参数

 1 export const appendQuery = (url, key, value) => {
 2     var options = key;
 3     if (typeof options == ‘string‘) {
 4         options = {};
 5         options[key] = value;
 6     }
 7     options = $.param(options);
 8     if (url.includes(‘?‘)) {
 9         url += ‘&‘ + options
10     } else {
11         url += ‘?‘ + options
12     }
13     return url;
14 }

 

 原网址:https://segmentfault.com/a/1190000022736837

前端常用工具方法

标签:define   翻译   新疆   dex   iphone   ops   err   fse   之间   

原文地址:https://www.cnblogs.com/xfcao/p/13061538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!