Say goodbye to the help of search engines and improve your development efficiency

1. Email

export const isEmail = (e) = > {
return / ^ ([a - zA - Z0 - _ - 9]) + @ ([a zA - Z0 - _ - 9]) + ((. [a zA - Z0 - _ - 9] {2, 3})} {1, 2) $/.test(e)
}
Copy the code

2. Mobile phone number

export const isMobile = (e) = > {
return / [0-9] {10} ^ 1 $/.test(e)
}
Copy the code

3. Phone number

export const isPhone = (e) = >{
return / ^ ([0-9] {3, 4} -)? [0-9] {7, 8} $/.test(e)
}
Copy the code

4. Check whether the URL is available

export const isURL = (e) = > {
return /^http[s]? : \ \ /. * /.test(e)
}
Copy the code

5. Check whether it is a string

export const isNumber = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='String'
}
Copy the code

6. Determine whether to use a number

export const isNumber = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Number'
}
Copy the code

7. If a Boolean

export const isBoolean = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Boolean'
}
Copy the code

8. Function

export const isFunction = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Function'
}
Copy the code

9. Check whether the value is null

export const isNull = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Null'
}
Copy the code

10. Is undefined

export const isUndefined = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Undefined'
} 
Copy the code

11. Object or not

export const isObject = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Object'
}
Copy the code

12. Array or not

export const isArray = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Array'
} 
Copy the code

13. Time

export const isDate = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Date'
} 
Copy the code

14. Whether is regular

export const isRegExp = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='RegExp'
}
Copy the code

15. Check whether the object is incorrect

export const isError = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Error'
}
Copy the code

16. Is it a Symbol function

export const isSymbol = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Symbol'
}
Copy the code

17. Whether or not you Promise something

export const isPromise = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Promise'
}
Copy the code

18. Determine whether to Set an object

export const isSet = (e) = >{
return Object.prototype.toString.call(e).slice(8, -1) = = ='Set'
}
export const us = navigator.userAgent.toLowerCase();
Copy the code

19. Is it a wechat browser

export const isWeiXin = () = >{
return ua.match(/microMessenger/i) = ='micromessenger'
}
Copy the code

20. Check whether it is a mobile terminal

export const isDeviceMobile =() = >{
return /android|webos|iphone|ipod|balckberry/i.test(ua)
}
Copy the code

21. Is it a QQ browser

export const isQQBrowser = () = >{
return!!!!! ua.match(/mqqbrowser|qzone|qqbrowser|qbwebviewtype/i)}Copy the code

22. Is it a reptile

export const isSpider =() = >{
return /adsbot|googlebot|bingbot|msnbot|yandexbot|baidubot|robot|careerbot|seznambot|bot|baiduspider|jikespider|symantecspider| scannerlwebcrawler|crawler|360spider|sosospider|sogou web sprider|sougou orion spider/.test(ua)
}
Copy the code

23. If the ios

export const isIos =() = >{
var u = navigator.userAgent;
if(u.indexOf('Android') > -1||u.indexOf('Linux') > -1) {// Android phone
return false
}else if(u.indexOf('iPhone') > -1) {// iPhone
return true
}else if(u.indexOf('iPad') > -1) {//iPad
return false
}else if(u.indexOf('windows Phone') > -1) {/ / winphone mobile phones
return false
}else{
return false}}Copy the code

24. Check whether it is on a PC

export const isPC = () = >{
var userAgentInfo = navigator.userAgent
var Agents = ['Android'.'iPhone'.'SymbuanOS'.'Windows Phone'.'iPad'.'iPod'];
var flag = true;
for(var i = 0; i<Agents.length; i++){if(userAgentInfo.indexOf(Agents[i])>0){
flag = false;
break; }}return flag;
}
Copy the code

25. Remove HTML tags

export const removehtmltag = (str) = >{
return str.replace(/<[^>]+>/g.' ')}Copy the code

26. Obtain URL parameters

export const getQueryString =(name) = >{
const reg = new RegExp('(^ | &)'+name+'= (/ ^ & *) (& | $)'.'i');
const search = window.location.search.split('? ') [1] | |' ';
const r = search.match(reg) || [];
return r[2];
}
Copy the code

Dynamically introduce JS

export const injectScript =(src) = >{
const s = document.createElement('script');
s.type = 'text/JavaScript';
s.async = true;
s.src = src;
const t = document.getElentsByTagName('script') [0];
t.parentNode.insertBefore(s,t)
}
Copy the code

28. Download it according to the URL

export const download = (url) = >{
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
if(isChrome || isSafari){
var link = document.createElement('a');
link.href = url;
if(link.download ! = =undefined) {var fileName = url.substring(url.lastIndexOf('/') +1,url.length);
link.download = fileName
}
if(document.createEvent){
var e = document.createEvent('MouseEvents');
e.initEvent('click'.true.true);
link.dispatchEvent(e);
return true; }}if(url.indexOf('? ') = = = -1){
url+='? download'
}
window.open(url,'_self');
return true;
}
Copy the code

29. Whether el contains a class

export const hasClass = (el,className) = >{
let reg = new RegExp('(^|\\s)'+className+'(\\s|$)')
return reg.test(el.className)
}
Copy the code

30. El Adds a class

export const addClass = (el,className) = >{
if(hasClass(el,className)){
return
}
let newClass = el.className.split(' ')
newClass.push(className)
el.className = newClass.join(' ')}Copy the code

31. El removes a class

export cosnt removeClass = (el,className) = >{
if(! hasClass(el,className)){return
}
let reg = new RegExp('(^|\\s)'+className+'(\\s|$)'.'g')
el.className = el.className.replace(reg,' ')}Copy the code

32. Get the scroll coordinates

export const getScrollPosition = (el = window) = > ({
x:el.pageXOffset ! = =undefined ? el.pageXOffset : el.scrollLeft,
y:el.pageYOffset ! = =undefined ? el.pageYOffset : el.scrollTop
})
Copy the code

33. Scroll to the top

export cosnt scrollToTop = () = >{
const c = document.documentElement.scrollTop || document.body.scrollTop;
if(c>0) {window.requestAnimationFrame(scrollToTop);
window.scrollTo(0,c-c/8); }}Copy the code

34. Is el in viewport range

export const elementIsVisibleInViewport = (el,partiallyVisib = false) = >{
cosnt {top,left,right,bottom} = el.getBoundingClienRect();
const {innerHeight,innerWidth} = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}
Copy the code

35. Shuffle algorithm is random

export const shuffle = (arr) = > { 
var result = [],
random;
while (arr.length > 0) { 
random = Math.floor(Math.random() * arr.length); result.push(arr[random])
arr.splice(random, 1)}return result;
}
Copy the code

36. Block sticky boards

export const copyTextToClipboard = (value) = > { 
var textArea = document.createElement("textarea"); textArea.style.background = 'transparent'; 
textArea.value = value;
document.body.appendChild(textArea);
textArea.select(); 
try { 
var successful = document.execCommand('copy'); 
} catch (err) { 
console.log('Oops, unable to copy'); 
} 
document.body.removeChild(textArea); 
}
Copy the code

37. Determine the type set

export const checkStr = (str, type) = > { 
switch (type) { 
case 'phone':
// Mobile phone number
return / ^ 1 [3 4 5 6 7 | | | | | | 8, 9] [0-9] {9} $/.test(str); 
case 'tel':
/ / machine
return / ^ (0 \ d {2, 3} - \ d {7, 8}) (\ d {1, 4})? $/.test(str);
case 'card':
/ / id card
return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str); 
case 'pwd':
// The password must start with a letter and contain 6 to 18 letters, digits, and underscores (_)
return / ^ \ [a zA - Z] $/ w {5} in 2.test(str)
case 'postal':
// Zip code
return /[1-9]\d{5}(? ! \d)/.test(str);
case 'QQ':
/ / QQ number
return / ^ (1-9] [0-9] {4, 9} $/.test(str);
case 'email':
/ / email
return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); 
case 'money':
// Amount (2 decimal places)
return /^\d*(? : \ \ d {0, 2})? $/.test(str);
case 'URL':
/ / url
return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])? /.test(str) 
case 'IP': 
//IP
return / ((? : (? :25[0-5]|2[0-4]\\d|[01]? \\d? \\d)\\.) {3} (? :25[0-5]|2[0-4]\\d|[01]? \\d? \\d))/.test(str); 
case 'date':
// Date time
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) case 'number':
/ / digital
return $/ / ^ [0-9].test(str);
case 'english':
/ / English
return /^[a-zA-Z]+$/.test(str);
case 'chinese': 
/ / Chinese
return /^[\\u4E00-\\u9FA5]+$/.test(str);
case 'lower':
/ / lowercase
return /^[a-z]+$/.test(str);
case 'upper':
/ / the capital
return /^[A-Z]+$/.test(str);
case 'HTML': 
/ / HTML tags
return / < (" [^ "] * '|' [^ '] * '| [^' "> >]) * /.test(str); 
default: 
return true; }}Copy the code

Strict verification of id cards

export const isCardID =(sId) = >{
if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) {
console.log('Wrong id card length or format you entered')
return false 
}
// Id city
var aCity = { 11: "Beijing".12: "Tianjin".13: "Hebei".14: "Shanxi".15: Inner Mongolia.21: "Liaoning".22: "Jilin".23: "Heilongjiang".31: "Shanghai".32: "Jiangsu".33: "Zhejiang".34: "Anhui province".35: "Fujian".36: "Jiangxi".37: "Shandong".41: "Henan".42: "Hubei".43: "Hunan".44: "Guangdong".45: "Guangxi".46: "Hainan".50: "Chongqing".51: "Sichuan".52: "Guizhou".53: "Yunnan".54: "Tibet".61: "Shaanxi".62: "Gansu".63: "Qinghai".64: "The ningxia".65: "Xinjiang".71: "Taiwan".81: "Hong Kong".82: "Macau".91: "Foreign" };
if(! aCity[parseInt(sId.substr(0.2))]) { 
console.log('Your ID card is illegal in the district')
return false
}
// Date of birth verification
var sBirthday = (sId.substr(6.4) + "-" + Number(sId.substr(10.2)) + "-" + Number(sId.substr(12.2))).replace(/-/g."/"), d = new Date(sBirthday) 
if(sBirthday ! = (d.getFullYear() +"/" + (d.getMonth() + 1) + "/" + d.getDate())) { 
console.log('The date of birth on the ID card is illegal') 
return false 
}
// Check id number
var sum = 0, weights = [7.9.10.5.8.4.2.1.6.3.7.9.10.5.8.4.2],
codes = "10X98765432" 
for (var i = 0; i < sId.length - 1; i++) { 
sum += sId[i] * weights[i]; 
} 
var last = codes[sum % 11];
// The last digit of the calculated ID card number
if (sId[sId.length - 1] != last) { 
console.log('The ID number you entered is illegal') 
return false 
}
return true
}
Copy the code

39. Random number range

export const random = (min, max) = > { 
if (arguments.length === 2) { 
return Math.floor(min + Math.random() * ((max + 1) - min)) 
} else { 
return null; }}Copy the code

40. Translate Arabic numerals into Uppercase Chinese numerals

export const numberToChinese = (num) = > {
var AA = new Array("Zero"."一"."二"."Three"."Four"."Five"."Six"."Seven"."Eight"."Nine"."Ten");
var BB = new Array(""."Ten"."Best"."仟"."萬"."億"."Point".""); 
var a = ("" + num).replace(/(^0*)/g."").split("."), k = 0, re = "";
for (var i = a[0].length - 1; i >= 0; i--) { 
switch (k) { 
case 0: re = BB[7] + re;
break; 
case 4:
if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "} $") .test(a[0])) re = BB[4] + re;
break;
case 8:
re = BB[5] + re; BB[7] = BB[5]; k = 0;
break;
}
if (k % 4= =2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) = =0) re = AA[0] + re;
if (a[0].charAt(i) ! =0) re = AA[a[0].charAt(i)] + BB[k % 4] + re; k++; }
if (a.length > 1) { re += BB[6]; 
for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
} 
if (re == 'ten') re = "Ten";
if (re.match(A / / ^) && re.length == 3) re = re.replace("一".""); return re;
}
Copy the code

41. Convert numbers to uppercase amounts

export const changeToChinese = (Num) = > {
// Convert to character if not character is passed in
if (typeof Num == "number") { 
Num = new String(Num);
};
Num = Num.replace(/,/g."") 
// Replace ", "in tomoney().
Num = Num.replace(/ /g."") 
// Replace the space in tomoney()
Num = Num.replace(RMB/g /."") 
// Replace the possible ¥character
if (isNaN(Num)) { 
// Verify that the input character is a number
//alert(" Please check if the lower case amount is correct ");
return "";
}; 
// Start conversion after character processing
var part = String(Num).split(".");
var newchar = ""; 
// Convert before the decimal point
for (var i = part[0].length - 1; i >= 0; i--) { 
if (part[0].length > 10) { 
return ""; 
// If the number exceeds one billion units, prompt
} 
var tmpnewchar = ""
var perchar = part[0].charAt(i); 
switch (perchar) {
case "0":
tmpnewchar = "Zero" + tmpnewchar;
break;
case "1": 
tmpnewchar = "One" + tmpnewchar; 
break;
case "2":
tmpnewchar = "贰" + tmpnewchar; 
break;
case "3":
tmpnewchar = "叁" + tmpnewchar;
break;
case "4": tmpnewchar = "Boss" + tmpnewchar;
break;
case "5": tmpnewchar = "Wu" + tmpnewchar;
break;
case "6": tmpnewchar = "Lu" + tmpnewchar; 
break;
case "Seven": tmpnewchar = "Pure" + tmpnewchar;
break; 
case "8": tmpnewchar = "" + tmpnewchar; 
break; 
case "9": tmpnewchar = "Nine" + tmpnewchar;
break;
}
switch (part[0].length - i - 1) {
case 0: 
tmpnewchar = tmpnewchar + "Yuan";
break; 
case 1:
if(perchar ! =0) tmpnewchar = tmpnewchar + "Pick up"; 
break;
case 2: 
if(perchar ! =0) tmpnewchar = tmpnewchar + "Hk";
break; 
case 3: 
if(perchar ! =0) tmpnewchar = tmpnewchar + "仟";
break; 
case 4: 
tmpnewchar = tmpnewchar + "万"; 
break; 
case 5:
if(perchar ! =0) tmpnewchar = tmpnewchar + "Pick up";
break;
case 6:
if(perchar ! =0) tmpnewchar = tmpnewchar + "Hk";
break;
case 7:
if(perchar ! =0) tmpnewchar = tmpnewchar + "仟"; 
break; 
case 8:
tmpnewchar = tmpnewchar + "亿"; 
break; 
case 9: 
tmpnewchar = tmpnewchar + "Pick up"; 
break;
} 
var newchar = tmpnewchar + newchar; 
}
// Convert after the decimal point
if (Num.indexOf(".") != -1) {
if (part[1].length > 2) {
// alert(" Only two digits after the decimal point can be saved, the system will truncate automatically ")
);
part[1] = part[1].substr(0.2)}for (i = 0; i < part[1].length; i++) {
tmpnewchar = "" perchar = part[1].charAt(i) 
switch (perchar) { 
case "0":
tmpnewchar = "Zero" + tmpnewchar;
break;
case "1": 
tmpnewchar = "One" + tmpnewchar;
break; 
case "2":
tmpnewchar = "贰" + tmpnewchar;
break;
case "3":
tmpnewchar = "叁" + tmpnewchar;
break;
case "4": 
tmpnewchar = "Boss" + tmpnewchar;
break; 
case "5":
tmpnewchar = "Wu" + tmpnewchar;
break; 
case "6":
tmpnewchar = "Lu" + tmpnewchar;
break;
case "Seven": tmpnewchar = "Pure" + tmpnewchar; 
break; 
case "8":
tmpnewchar = "" + tmpnewchar;
break;
case "9": 
tmpnewchar = "Nine" + tmpnewchar; 
break; 
} 
if (i == 0) tmpnewchar = tmpnewchar + "Angle"; 
if (i == 1) tmpnewchar = tmpnewchar + "Points"; newchar = newchar + tmpnewchar; }}// Replace all useless Chinese characters
while (newchar.search("Zero zero.") != -1) 
newchar = newchar.replace("Zero zero."."Zero"); 
newchar = newchar.replace("LingYi"."亿"); 
newchar = newchar.replace("Hundreds of millions"."亿"); 
newchar = newchar.replace("LingWan"."万"); 
newchar = newchar.replace("Zero yuan"."Yuan"); 
newchar = newchar.replace("Zero Angle".""); 
newchar = newchar.replace("Zero".""); 
if (newchar.charAt(newchar.length - 1) = ="Yuan") { 
newchar = newchar + "The whole" 
} 
return newchar;
}
Copy the code

42. Check if an element is in an array

export const contains = (arr, val) = > { 
returnarr.indexOf(val) ! = -1 ? true : false; 
}
Copy the code

43. Array sort {type} 1: from smallest to largest 2: from largest to smallest 3: random

export const sort = (arr, type = 1) = > {
return arr.sort((a, b) = > { 
switch (type) { 
case 1:
return a - b;
case 2:
return b - a;
case 3: 
return Math.random() - 0.5;
default:
returnarr; }})}Copy the code

44. To weight

export const unique = (arr) = > { 
if (Array.hasOwnProperty('from')) { 
return Array.from(new Set(arr));
} else { 
var n = {},
r = []; 
for (var i = 0; i < arr.length; i++) { 
if(! n[arr[i]]) { n[arr[i]] =true; r.push(arr[i]); }}returnr; }}Copy the code

Find the union of two sets

export const union = (a, b) = > { 
var newArr = a.concat(b); 
return this.unique(newArr); 
}
Copy the code

Find the intersection of two sets

export const intersect = (a, b) = > {
var _this = this;
a = this.unique(a);
return this.map(a, function (o) { 
return _this.contains(b, o) ? o : null; });
}
Copy the code

47. Delete one element

export const remove = (arr, ele) = > { 
var index = arr.indexOf(ele); 
if (index > -1) { 
arr.splice(index, 1); 
}
return arr; 
}
Copy the code

48. Convert class arrays to arrays

export const formArray = (ary) = > { 
var arr = [];
if (Array.isArray(ary)) {
arr = ary;
} else {
arr = Array.prototype.slice.call(ary); 
}; 
return arr; 
}
Copy the code

The maximum value of 49.

export const max = (arr) = > { 
return Math.max.apply(null, arr); 
}
Copy the code

50. The minimum value

export const min = (arr) = > { 
return Math.min.apply(null, arr); 
}
Copy the code

51. The sum

export const sum = (arr) = > { 
return arr.reduce((pre, cur) = > { return pre + cur }) 
}
Copy the code

The average 52.

export const average = (arr) = > {
return this.sum(arr) / arr.length 
}
Copy the code

53. Remove Spaces,type: 1- all Spaces 2- front and rear Spaces 3- front Spaces 4- back Spaces

export const trim = (str, type) = > {
type = type || 1 
switch (type) { 
case 1: 
return str.replace(/\s+/g."");
case 2:
return str.replace(/(^\s*)|(\s*$)/g."");
case 3:
return str.replace(/(^\s*)/g."");
case 4: 
return str.replace(/(\s*$)/g.""); 
default: 
returnstr; }}Copy the code

54. Character conversion, type: 1: uppercase letters 2: lowercase letters 3: uppercase letters 4: all uppercase letters 5: all lowercase letters

export const changeCase = (str, type) = > { 
type = type || 4 
switch (type) {
case 1: 
return str.replace(/\b\w+\b/g.function (word) { 
return word.substring(0.1).toUpperCase() + word.substring(1).toLowerCase(); 
});
case 2: 
return str.replace(/\b\w+\b/g.function (word) { 
return word.substring(0.1).toLowerCase() + word.substring(1).toUpperCase(); 
}); 
case 3:
return str.split(' ').map(function (word) { 
if (/[a-z]/.test(word)) { 
return word.toUpperCase();
} else { 
return word.toLowerCase() } 
}).join(' ')
case 4:
return str.toUpperCase();
case 5: 
return str.toLowerCase();
default:
returnstr; }}Copy the code

55. Detect password strength

export const checkPwd = (str) = > {
var Lv = 0; 
if (str.length < 6) { 
return Lv 
} 
if (/ [0-9].test(str)) { Lv++ } 
if (/[a-z]/.test(str)) { Lv++ }
if (/[A-Z]/.test(str)) { Lv++ } 
if (/ [\ | | _] /.test(str)) { Lv++ }
return Lv; 
}
Copy the code

56. Function throttle

export const debouncer = (fn, time, interval = 200) = > { 
if (time - (window.debounceTimestamp || 0) > interval) {
fn && fn();
window.debounceTimestamp = time; }}Copy the code

57. Insert a new string into a string

export const insertStr = (soure, index, newStr) = > {
var str = soure.slice(0, index) + newStr + soure.slice(index); return str; 
}
Copy the code

58. Determine whether two objects have the same key value

export const isObjectEqual = (a, b) = > { 
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b); 
if(aProps.length ! == bProps.length) {return false; 
} 
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i]; 
if(a[propName] ! == b[propName]) {return false; }}return true;
}
Copy the code

59.hexadecimal color transfer RGBRGBA string

export const colorToRGB = (val, opa) = > { 
var pattern = / ^ (#? [a-fA-F0-9]{6}$/; 
// Hexadecimal color check rule
var isOpa = typeof opa == 'number';
// Check if opacity is set
if(! pattern.test(val)) {// Returns a null character if the value does not conform to the rule
return ' '; 
} 
var v = val.replace(/ # /.' '); 
// If there are # signs, remove # signs first
var rgbArr = [];
var rgbStr = ' ';
for (var i = 0; i < 3; i++) { 
var item = v.substring(i * 2, i * 2 + 2);
var num = parseInt(item, 16); 
rgbArr.push(num); 
}
rgbStr = rgbArr.join();
rgbStr = 'rgb' + (isOpa ? 'a' : ' ') + '(' + rgbStr + (isOpa ? ', ' + opa : ' ') + ') ';
return rgbStr;
}
Copy the code

60. Append URL parameters

export const appendQuery = (url, key, value) = > { 
var options = key;
if (typeof options == 'string') {
options = {}; 
options[key] = value;
} 
options = $.param(options);
if (url.includes('? ')) {
url += '&' + options 
} else { 
url += '? ' + options 
}
return url; 
}
Copy the code