1. Mailbox
export const isEmail = (s) => {
return /^([a-zA-Z0-9_-])[email protected]([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}
2. Mobile phone number
export const isMobile = (s) => {
return /^1[0-9]{10}$/.test(s)
}
3. Telephone number
export const isPhone = (s) => {
return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)
}
4. URL address
export const isURL = (s) => {
return /^http[s]?:\/\/.*/.test(s)
}
5. String
export const isString = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'String'
}
6. Are there any numbers
export const isNumber = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Number'
}
7. Boolean
export const isBoolean = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean'
}
8. Function
export const isFunction = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Function'
}
9. Is it null
export const isNull = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Null'
}
10. Is it undefined
export const isUndefined = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined'
}
11. Object
export const isObj = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Object'
}
12. Array
export const isArray = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Array'
}
13. Whether the time
export const isDate = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Date'
}
14. Regular
export const isRegExp = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'RegExp'
}
15. Wrong object
export const isError = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Error'
}
16. Symbol function
export const isSymbol = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Symbol'
}
17. Promise object
export const isPromise = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Promise'
}
18. Set object
export const isSet = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Set'
}
export const ua = navigator.userAgent.toLowerCase();
19. Is it a wechat browser
export const isWeiXin = () => {
return ua.match(/microMessenger/i) == 'micromessenger'
}
20. Is it a mobile terminal
export const isDeviceMobile = () => {
return /android|webos|iphone|ipod|balckberry/i.test(ua)
}
21. Is it a QQ browser
export const isQQBrowser = () => {
return !!ua.match(/mqqbrowser|qzone|qqbrowser|qbwebviewtype/i)
}
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|sogou orion spider/.test(ua)
}
23. Is it 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) {// Apple phone
return true
} else if (u.indexOf('iPad') > -1) {//iPad
return false
}Else if (u.indexof ('windows phone ') > - 1) {// winphone phone phone
return false
} else {
return false
}
}
24. Is it PC terminal
export const isPC = () => {
var userAgentInfo = navigator.userAgent;
var Agents = ["Android", "iPhone",
"SymbianOS", "Windows Phone",
"iPad", "iPod"];
var flag = true;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = false;
break;
}
}
return flag;
}
25. Remove HTML tags
export const removeHtmltag = (str) => {
return str.replace(/<[^>]+>/g, '')
}
26. Get 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];
}
27. Dynamic introduction of JS
export const injectScript = (src) => {
const s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = src;
const t = document.getElementsByTagName('script')[0];
t.parentNode.insertBefore(s, t);
}
28. Download according to the URL address
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;
}
29. Does El contain a class
export const hasClass = (el, className) => {
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
return reg.test(el.className)
}
30.el add a class
export const addClass = (el, className) => {
if (hasClass(el, className)) {
return
}
let newClass = el.className.split(' ')
newClass.push(className)
el.className = newClass.join(' ')
}
31.el remove a class
export const removeClass = (el, className) => {
if (!hasClass(el, className)) {
return
}
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g')
el.className = el.className.replace(reg, ' ')
}
32. Obtain the coordinates of the scroll
export const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
33. Scroll to top
export const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
34. Is El within the viewport
export const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
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;
}
35. Shuffle algorithm 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;
}
36. Intercepting adhesive board
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);
}
37. Judgment type set
export const checkStr = (str, type) => {
switch (type) {
Case 'phone': // phone number
return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
Case 'Tel': // landline
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 starts with a letter and is between 6 and 18 in length. It can only contain letters, numbers and underscores
return /^[a-zA-Z]\w{5,17}$/.test(str)
Case 'postal': // postal code
return /[1-9]\d{5}(?!\d)/.test(str);
Case 'QQ': // QQ No
return /^[1-9][0-9]{4,9}$/.test(str);
Case 'email': // mailbox
return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
Case 'money': // amount (2 decimal places)
return /^\d*(?:\.\d{0,2})?$/.test(str);
Case 'URL': // Web address
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 and 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': // number
return /^[0-9]$/.test(str);
Case 'English': // English
return /^[a-zA-Z]+$/.test(str);
Case 'Chinese': // Chinese
return /^[\\u4E00-\\u9FA5]+$/.test(str);
Case 'lower': // lower case
return /^[a-z]+$/.test(str);
Case 'upper': // upper case
return /^[A-Z]+$/.test(str);
Case 'HTML': // HTML tag
return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
default:
return true;
}
}
38. Strict ID verification
export const isCardID = (sId) => {
if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) {
console. Log ('the length or format of the ID card you entered is incorrect ')
return false
}
//ID card 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", 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: "Ningxia", 65: "Xinjiang", 71: "Taiwan", 81: "Hong Kong", 82: "Macao", 91: "foreign"};
if (!aCity[parseInt(sId.substr(0, 2))]) {
console. Log ('your ID card area is illegal ')
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 ('illegal birth date on ID card ')
return false
}
// ID number verification
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 ID number calculated.
if (sId[sId.length - 1] != last) {
console. Log ("you enter the ID number illegal")
return false
}
return true
}
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;
}
}
40. Translate Arabic numerals into Chinese capital numerals
export const numberToChinese = (num) => {
Var AA = new array ("zero", "one", "two", "three", "four", "Five", "six", "seven", "eight", "Nine", "ten");
Var BB = new array ("", "ten", "hundred", "thousand", "ten thousand", "hundred million", "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) // add the decimal part (if any)
{
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) & & re length == 3)
re = re. Replace ("one", "");
return re;
}
41. Convert figures to words
export const changeToChinese = (Num) => {
//Judge if the passed in is not a character, convert it to a character
if (typeof Num == "number") {
Num = new String(Num);
};
Num = num.replace (/, / g, "") // replace "," in tomoney()
Num = num.replace (// g, "") // replace spaces in tomoney()
Num = num.replace (/ ¥ / g, "") // replace the possible ¥ characters
If (IsNaN (Num)) {// verify that the entered character is a number
//Alert ("please check whether the amount in figures is correct");
return "";
};
//The conversion starts after the character processing, and the front and rear parts are used for conversion respectively
var part = String(Num).split(".");
var newchar = "";
//Convert before decimal point
for (var i = part[0].length - 1; i >= 0; i--) {
if (part[0].length > 10) {
return "";
//If the quantity 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 = "two" + tmpnewchar;
break;
case "3":
Tmpnewchar = "three" + tmpnewchar;
break;
case "4":
Tmpnewchar = "four" + tmpnewchar;
break;
case "5":
Tmpnewchar = "Five" + tmpnewchar;
break;
case "6":
Tmpnewchar = "land" + tmpnewchar;
break;
case "7":
Tmpnewchar = "seven" + tmpnewchar;
break;
case "8":
Tmpnewchar = "eight" + 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";
break;
case 2:
If (perchar! = 0) tmpnewchar = tmpnewchar + "Bai";
break;
case 3:
If (perchar! = 0) tmpnewchar = tmpnewchar + "thousand";
break;
case 4:
Tmpnewchar = tmpnewchar + "ten thousand";
break;
case 5:
If (perchar! = 0) tmpnewchar = tmpnewchar + "pick";
break;
case 6:
If (perchar! = 0) tmpnewchar = tmpnewchar + "Bai";
break;
case 7:
If (perchar! = 0) tmpnewchar = tmpnewchar + "thousand";
break;
case 8:
Tmpnewchar = tmpnewchar + "100 million";
break;
case 9:
Tmpnewchar = tmpnewchar + "ten";
break;
}
var newchar = tmpnewchar + newchar;
}
//Convert after decimal point
if (Num.indexOf(".") != -1) {
if (part[1].length > 2) {
//Alert ("only two digits can be reserved after the decimal point, and the system will automatically truncate");
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 = "two" + tmpnewchar;
break;
case "3":
Tmpnewchar = "three" + tmpnewchar;
break;
case "4":
Tmpnewchar = "four" + tmpnewchar;
break;
case "5":
Tmpnewchar = "Five" + tmpnewchar;
break;
case "6":
Tmpnewchar = "land" + tmpnewchar;
break;
case "7":
Tmpnewchar = "seven" + tmpnewchar;
break;
case "8":
Tmpnewchar = "eight" + tmpnewchar;
break;
case "9":
Tmpnewchar = "Nine" + tmpnewchar;
break;
}
If (I = = 0) tmpnewchar = tmpnewchar + "angle";
If (I = = 1) tmpnewchar = tmpnewchar + "minute";
newchar = newchar + tmpnewchar;
}
}
//Replace all useless Chinese characters
While (newchar. Search ("zero")! =- 1)
newchar = newchar. Replace ("zero", "zero");
newchar = newchar. Replace ("billion");
newchar = newchar. Replace ("billions", "billions");
newchar = newchar. Replace ("ten thousand", "ten thousand");
newchar = newchar. Replace ("zero yuan", "Yuan");
newchar = newchar. Replace ("zero angle", "");
newchar = newchar. Replace ("zero", "");
If (newchar. Charat (newchar. Length - 1) = = "Yuan"){
Newchar = newchar + "integer"
}
return newchar;
}
42. Determine whether an element is in the array
export const contains = (arr, val) => {
return arr.indexOf(val) != -1 ? true : false;
}
43. Array sorting, {type} 1: from small to large 2: from large to small 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:
return arr;
}
})
}
44. Weight removal
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]);
}
}
return r;
}
}
45. Find the union of two sets
export const union = (a, b) => {
var newArr = a.concat(b);
return this.unique(newArr);
}
46. 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;
});
}
47. Delete one of the elements
export const remove = (arr, ele) => {
var index = arr.indexOf(ele);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
48. Convert class array to array
export const formArray = (ary) => {
var arr = [];
if (Array.isArray(ary)) {
arr = ary;
} else {
arr = Array.prototype.slice.call(ary);
};
return arr;
}
49. Max
export const max = (arr) => {
return Math.max.apply(null, arr);
}
50. Min
export const min = (arr) => {
return Math.min.apply(null, arr);
}
51. Summation
export const sum = (arr) => {
return arr.reduce((pre, cur) => {
return pre + cur
})
}
52. Average value
export const average = (arr) => {
return this.sum(arr) / arr.length
}
53. Remove spaces, type: 1 – all spaces, 2 – front and rear spaces, 3 – front spaces, 4 – rear 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:
return str;
}
}
54. Character conversion, type: 1: initial uppercase 2: initial lowercase 3: case conversion 4: all uppercase 5: all lowercase
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:
return str;
}
}
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;
}
56. Function restrictor
export const debouncer = (fn, time, interval = 200) => {
if (time - (window.debounceTimestamp || 0) > interval) {
fn && fn();
window.debounceTimestamp = time;
}
}
57. Insert a new string into the string
export const insertStr = (soure, index, newStr) => {
var str = soure.slice(0, index) + newStr + soure.slice(index);
return str;
}
58. Judge 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;
}
59. Hexadecimal color to rgbrgba string
export const colorToRGB = (val, opa) => {
var pattern = /^(#?) [a-fA-F0-9]{6}$/; // Hex color value verification rules
var isOpa = typeof opa == 'number'; // Determine whether opacity is set
If (! Pattern. Test (VAL)) {// if the value does not conform to the rules, an empty character is returned
return '';
}
var v = val.replace(/#/, ''); // If there is a # number, remove the # number 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;
}
60. Add URL parameter
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;
}