preface

In our daily development, we may encounter various needs, but we may not find the right way to solve them for a while. The following JavaScript tool functions may come in handy, and we can reuse them to improve our work efficiency.

I put the following methods in a rough class on my GitHub. You can clone it and use it directly, or you can look it up when you need it, using CTRL +F. This repository will also be updated, if there is not, but need to use the tool function, you can also put forward in the issues, maybe to help others oh ~

Regex check utility function

The regular expression here mainly refers to any-rule.

Validation cannot contain letters

/**
 * @param { string } value
 */
export const isNoWord = value => /^[^A-Za-z]*$/g.test(value);Copy the code

Verify Chinese and numbers

/** * @param { string } value */ export const isCHNAndEN = value => /^((? :[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\u D86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD 86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])|(\d))+$/g.test(value);Copy the code

Verify zip Code (China)

/**
 * @param { string } value
 */
export const isPostcode = value => /^(0[1-7]|1[0-356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[0-5]|8[013-6])\d{4}$/g.test(value);Copy the code

Verify wechat id, 6 to 20 digits, beginning with a letter, letter, digit, minus sign, underscore

/** * @param {string} value */ export const isWeChatNum = value => /^[a-za-z][-_a-za-z0-9]{5,19}$/g.test(value);Copy the code

### Verify hexadecimal colors

/** * @param { string } value */ export const isColor16 = value => /^#? ([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/g.test(value);Copy the code

Verify the train number

/** * @param {string} value */ export const isTrainNum = value => /^[gcdztspkxly1-9]\d{1,4}$/g.test(value); /** * @param {string} value */ export const isTrainNum = value => /^[gcdztspkxly1-9]\d{1,4}$/g.test(value);Copy the code

Verify the phone body Code (IMEI)

/** * @param {string} value */ export const isIMEI = value => /^\d{15,17}$/ g.est (value);Copy the code

Verify the url (or IP) that must have a port number

/** * @param { string } value */ export const isHttpAndPort = value => /^((ht|f)tps? : \ \ /)? [/ w] + (\ [/ w] +) + : \ d {1, 5} \ /? $/g.test(value);Copy the code

### verify url (support port and “? + parameter “and “#+ parameter)

/** * @param { string } value */ export const isRightWebsite = value => /^(((ht|f)tps?) : \ \ /)? [\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])? $/g.test(value);Copy the code

Verify the uniform social credit code

/**
 *  @param { string } value
 */
export const isCreditCode = value => /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/g.test(value);Copy the code

Verify the thunderbolt link

/** * @param { string } value */ export const isThunderLink = value => /^thunderx? :\/\/[a-zA-Z\d]+=$/g.test(value);Copy the code

### Verify ED2K links (loose matching)

/**
 *  @param { string } value
 */
export const ised2k = value => /^ed2k:\/\/\|file\|.+\|\/$/g.test(value);Copy the code

Verify magnetic links (loose matching)

/** * @param { string } value */ export const isMagnet = value => /^magnet:\? xt=urn:btih:[0-9a-fA-F]{40,}.*$/g.test(value);Copy the code

Verify the subnet mask

/** * @param { string } value */ export const isSubnetMask = value => /^(? D: \ \ d {1, 2} 1 \ | d | 2 \ [0-4] d | 25 ([0 to 5])? : \. (? : 1 \ \ d {1, 2} | d \ | 2 d \ [0-4] d | 25 [0-5])) {3} $/ g.t est (value);Copy the code

Verify the Linux folder path

/** * @param { string } value */ export const isLinuxFolderPath = value => /^(\/[^/]+)+\/? $/g.test(value);Copy the code

Verify the Linux “file” path

/**
 *  @param { string } value
 */
export const isLinuxFilePath = value => /^(\/[^/]+)+$/g.test(value);Copy the code

Verify the window folder path

/** * @param { string } value */ export const isWindowsFolderPath = value => /^[a-zA-Z]:\\(? :\w+\\?) *$/g.test(value);Copy the code

Verify the “file” path under Window

/** * @param { string } value */ export const isWindowsFilePath = value => /^[a-zA-Z]:\\(? :\w+\\)*\w+\.\w+$/g.test(value);Copy the code

Verify stock code (A-share)

/**
 *  @param { string } value
 */
export const isAShare = value => /^(s[hz]|S[HZ])(000[\d]{3}|002[\d]{3}|300[\d]{3}|600[\d]{3}|60[\d]{4})$/g.test(value);Copy the code

The verification version must be in the format of X.Y.Z

/** * @param { string } value */ export const isVersion = value => /^\d+(? :\.\d+){2}$/g.test(value);Copy the code

Verify video link address (video format can be added or deleted as required)

/** * @param { string } value */ export const isVideoUrl = value => /^https? :\/\/(.+\/)+.+(\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4))$/i.test(value);Copy the code

Verify image link address (image format can be added or deleted as required)

/** * @param { string } value */ export const isImageUrl = value => /^https? :\/\/(.+\/)+.+(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i.test(value);Copy the code

Verify bank card number (10 to 30 digits, covering public and private accounts, refer to wechat Pay)

/** * @param {string} value */ export const isAccountNumber = value => /^[1-9]\d{9,29}$/g.test(value); /** * @param {string} value */ export const isAccountNumber = value => /^[1-9]\d{9,29}$/g.test(value);Copy the code

Verify Chinese name

/** * @param { string } value */ export const isChineseName = value => /^(? : [the] \ u4e00 - \ u9fa5 16th {2}) $/ g.t est (value);Copy the code

Verify English name

/** * @param { string } value */ export const isEnglishName = value => / (^ {1} [a zA - Z] [a zA - Z \ s] {0, 20} [a zA - Z] {1} $)/g.t est (value);Copy the code

### Verify license plate number (new energy)

/** * @param {string} value */ export const isLicensePlateNumberNER = value => /** * @param {string} const isLicensePlateNumberNER = value => / A-Z]{1}[A-HJ-NP-Z]{1}(([0-9]{5}[DF])|([DF][A-HJ-NP-Z0-9][0-9]{4}))$/g.test(value);Copy the code

Verify license plate number (non-new energy)

/** * @param {string} value */ export const islicenseplatenumner = value => /** * @param {string} value */ export const islicenseplatenumner = value = A - Z] {1} [A - HJ - NP - Z] {1} {4} [A - Z0-9] [A - Z0-9 hang cop Hong Kong and Macao] {1} $/ g.t est (value);Copy the code

Verify license plate number (new energy + Non-new energy)

/** * @param { string } value */ export const isLicensePlateNumber = value => /^(? : {1}[a-hJ-NP-z]{1}(a-hJ-NP-z]{1}(? : (? :[0-9]{5}[DF])|(? :[DF](? :[A-HJ-NP-Z0-9])[0-9]{4})))|(? : [beijing-tianjin Shanghai yu ji yu cloud liao black xiang anhui new GuiGan of hubei province can Sue your yue jin meng shan ji min qinghai-tibet plain NingQiong that brought A - Z] {1} {1} [a-z] [A - HJ - NP - Z0-9] {4} [A - HJ - NP - Z0-9 hang cop Hong Kong and Macao] {1}) $/ g.t est (value);Copy the code

Verify mobile phone number China (rigorous), according to the latest mobile phone number segment released by the Ministry of Industry and Information Technology in 2019

/** * @param { string } value */ export const isMPStrict = value => /^(? : (? : \ | + 00) 86)? 1 (? : (? :3[\d])|(? : 4 [5-7 | 9]) | (? : 5 [0-3 | 5-9]) | (? : 6 [5-7]) | (? : 7-8 0) | (? :8[\d])|(? :9[1|8|9]))\d{8}$/g.test(value);Copy the code

Verify the phone number China (loose), as long as it starts with 13,14,15,16,17,18,19

/** * @param { string } value */ export const isMPRelaxed = value => /^(? : (? : \ | + 00) 86)? 1[3-9]\d{9}$/g.test(value);Copy the code

Verify email

/** * @param { string } value */ export const isEmail = value => /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](? : [a - zA - Z0-9 -], 21 {0} [a zA - Z0-9])? (? :\.[a-zA-Z0-9](? : [a - zA - Z0-9 -], 21 {0} [a zA - Z0-9])?) *$/g.test(value);Copy the code

Verify the landline number (domestic), for example: 0341-86091234

/**
 * @param { string } value
 */
export const isLandlineTelephone = value => /\d{3}-\d{8}|\d{4}-\d{7}/g.test(value);Copy the code

Verify ID number (1 generation,15 digits)

/**
 * @param { string } value
 */
export const isIDCardOld = value => /^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$/g.test(value);Copy the code

Verify the id number (2 generations,18 digits) with the last digit being the check bit, which may be a number or character X

/**
 * @param { string } value
 */
export const isIDCardNew = value => /^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}[\dXx]$/g.test(value);Copy the code

Verify ID number, support 1/2 generation (15 /18 digits)

/** * @param { string } value */ export const isIDCard = value => /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/g.test(v alue);Copy the code

Passport Verification (including Hong Kong and Macao)

/**
 * @param { string } value
 */
export const isPassport = value => /(^[EeKkGgDdSsPpHh]\d{8}$)|(^(([Ee][a-fA-F])|([DdSsPp][Ee])|([Kk][Jj])|([Mm][Aa])|(1[45]))\d{7}$)/g.test(value);Copy the code

Verify that the account is valid. The account starts with a letter and contains 5 to 16 bytes. Alphanumeric and underscore (_) are allowed

/** * @param {string} value */ export const isWebAccount = value => /^[a-za-z]\w{4,15}$/g.test(value);Copy the code

Verify Chinese/Chinese characters

/** * @param { string } value */ export const isChineseCharacter = value => /^(? :[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\u D86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD 86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])+$/g.test(value);Copy the code

Verify the decimal

/**
 * @param { string } value
 */
export const isDecimal = value => /^\d+\.\d+$/g.test(value);Copy the code

Verify the digital

/**
 * @param { string } value
 */
export const isNumber = value => /^\d{1,}$/g.test(value);Copy the code

Verify the QQ id format

/** * @param {string} value */ export const isQQNum = value => /^[1-9][0-9]{4,10}$/g.test(value);Copy the code

Verify the number and letter composition

/**
 * @param { string } value
 */
export const isNumAndStr = value => /^[A-Za-z0-9]+$/g.test(value);Copy the code

Verify English letters

/**
 * @param { string } value
 */
export const isEnglish = value => /^[a-zA-Z]+$/g.test(value);Copy the code

Verify uppercase English letters

/**
 * @param { string } value
 */
export const isCapital = value => /^[A-Z]+$/g.test(value);Copy the code

Verify lowercase letters

/**
 * @param { string } value
 */
export const isLowercase = value => /^[a-z]+$/g.test(value);Copy the code

Browser operation related browser tool functions

Return current URL

export const currentURL = () => window.location.href;Copy the code

Get URL parameters (the first kind)

/** * @param {*} name * @param {*} origin */ export function getUrlParam(name, origin = null) { let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); let r = null; if (origin == null) { r = window.location.search.substr(1).match(reg); } else { r = origin.substr(1).match(reg); } if (r ! = null) return decodeURIComponent(r[2]); return null; }Copy the code

Get URL parameters (second kind)

/** * @param {*} name * @param {*} origin */ export function getUrlParams(name, origin = null) { let url = location.href; let temp1 = url.split('? '); let pram = temp1[1]; let keyValue = pram.split('&'); let obj = {}; for (let i = 0; i < keyValue.length; i++) { let item = keyValue[i].split('='); let key = item[0]; let value = item[1]; obj[key] = value; } return obj[name]; }Copy the code

Modify parameters in the URL

/**
 * @param { string } paramName
 * @param { string } replaceWith
 */
export function replaceParamVal(paramName,replaceWith) {
    var oUrl = location.href.toString();
    var re=eval('/('+ paramName+'=)([^&]*)/gi');
    location.href = oUrl.replace(re,paramName+'='+replaceWith);
    return location.href;
}Copy the code

Deletes the parameter specified in the URL

/** * @param { string } name */ export function funcUrlDel(name){ var loca =location; var baseUrl = loca.origin + loca.pathname + "?" ; var query = loca.search.substr(1); if (query.indexOf(name)>-1) { var obj = {}; var arr = query.split("&"); for (var i = 0; i < arr.length; i++) { arr[i] = arr[i].split("="); obj[arr[i][0]] = arr[i][1]; } delete obj[name]; var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&"); return url } }Copy the code

Gets the height of the window’s viewable range

export function getClientHeight() {
    let clientHeight = 0;
    if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    return clientHeight;
}Copy the code

Gets the window viewable range width

export function getPageViewWidth() {
    let d = document,
        a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
    return a.clientWidth;
}Copy the code

Get window width

export function getPageWidth() {
    let g = document,
        a = g.body,
        f = g.documentElement,
        d = g.compatMode == "BackCompat" ? a : g.documentElement;
    return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
}Copy the code

Get window size

export function getViewportOffset() { if (window.innerWidth) { return { w: window.innerWidth, h: If (document.compatMode === "BackCompat") {// Eccentric mode return {w: Document. Body. ClientWidth, h: the document body. ClientHeight}} else {/ / standard model return {w: document.documentElement.clientWidth, h: document.documentElement.clientHeight } } } }Copy the code

Gets the height of the scroll bar from the top

export function getPageScrollTop() {
    let a = document;
    return a.documentElement.scrollTop || a.body.scrollTop;
}Copy the code

Gets the height to the left of the scrollbar pitch

export function getPageScrollLeft() {
    let a = document;
    return a.documentElement.scrollLeft || a.body.scrollLeft;
}Copy the code

Open the full screen

/**
 * @param {*} element
 */
export function launchFullscreen(element) {
    if (element.requestFullscreen) {
        element.requestFullscreen()
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen()
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen()
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullScreen()
    }
}Copy the code

Shut down full screen

export function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen()
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
    }
}Copy the code

Returns the current scrollbar position

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

Scroll to the specified element area

export const smoothScroll = element =>{
    document.querySelector(element).scrollIntoView({
        behavior: 'smooth'
    });
};Copy the code

Scroll smoothly to the top of the page

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

HTTP jump HTTPS

export const httpsRedirect = () => { if (location.protocol ! == 'https:') location.replace('https://' + location.href.split('//')[1]); };Copy the code

Check whether the bottom of the page is visible

export const bottomVisible = () =>{
    return document.documentElement.clientHeight + window.scrollY >=
        (document.documentElement.scrollHeight || document.documentElement.clientHeight);
};Copy the code

Open a window

/** * @param { string } url * @param { string } windowName * @param { number } width * @param { number } height */ Export function openWindow(url, windowName, width, height) {var x = parseInt(screen.width / 2.0) -width / 2.0; Var y = parseInt(screen.height / 2.0) -height / 2.0; var isMSIE = navigator.appName == "Microsoft Internet Explorer"; if (isMSIE) { var p = "resizable=1,location=no,scrollbars=no,width="; p = p + width; p = p + ",height="; p = p + height; p = p + ",left="; p = p + x; p = p + ",top="; p = p + y; window.open(url, windowName, p); } else { var win = window.open( url, "ZyiisPopup", "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=yes,modal=yes,width=" + width + ",height=" + height +  ",resizable=no" ); eval("try { win.resizeTo(width, height); } catch(e) { }"); win.focus(); }}Copy the code

Adaptive pages (REM)

/**
 * @param { number } width
 */
export function AutoResponse(width = 750) {
    const target = document.documentElement;
    target.clientWidth >= 600
        ? (target.style.fontSize = "80px")
        : (target.style.fontSize = target.clientWidth / width * 100 + "px");
}Copy the code

Date tool Date Tool function

Check out my other post “Various date manipulations on the front end,” or just go to my GitHub

The browser stores storage-related utility functions

Mainly for the browser storage aspects of the utility functions, most of the transport of the Big Fire Wolf 1

LocalStorage storage

* @param {String} key * @param {String} value */ export const localStorageSet = (key, value) => { if (typeof (value) === 'object') value = JSON.stringify(value); localStorage.setItem(key, value) };Copy the code

LocalStorage to obtain

/** * @param {String} key attributes */ export const localStorageGet = (key) => {return localstorage.getitem (key)};Copy the code

LocalStorage to remove

/** * @param {String} key attributes */ export const localStorageRemove = (key) => {localstorage.removeItem (key)};Copy the code

LocalStorage storage expires for a certain period of time

/** * @param {String} key attribute * @param {*} value Stored value * @param {number} expire time, milliseconds */ export const localStorageSetExpire = (key, value, expire) => { if (typeof (value) === 'object') value = JSON.stringify(value); localStorage.setItem(key, value); setTimeout(() => { localStorage.removeItem(key) }, expire) };Copy the code

SessionStorage storage

/** * @param {String} key attribute * @param {*} value value */ export const sessionStorageSet = (key, value) => { if (typeof (value) === 'object') value = JSON.stringify(value); sessionStorage.setItem(key, value) };Copy the code

SessionStorage access

/** * @param {String} key attributes */ export const sessionStorageGet = (key) => {return sessionStorage.getitem (key)};Copy the code

SessionStorage delete

/ * * * @ param {String} the key attribute * / export const sessionStorageRemove = (key) = > {sessionStorage. RemoveItem (key)};Copy the code

SessionStorage The storage expires for a certain period of time

/** * @param {String} key attribute * @param {*} value Stored value * @param {String} expire time, milliseconds */ export const sessionStorageSetExpire = (key, value, expire) => { if (typeof (value) === 'object') value = JSON.stringify(value); sessionStorage.setItem(key, value); setTimeout(() => { sessionStorage.removeItem(key) }, expire) };Copy the code

Cookie store

/** * @param {String} key attribute * @param {*} value value * @param {String} expire time */ export const cookieSet = (key, value, expire) => { const d = new Date(); d.setDate(d.getDate() + expire); document.cookie = `${key}=${value}; expires=${d.toUTCString()}` };Copy the code

Cookies for

/** * @param {String} key */ export const cookieGet = (key) => {const cookieStr = unescape(document.cookie); const arr = cookieStr.split('; '); let cookieValue = ''; for (let i = 0; i < arr.length; i++) { const temp = arr[i].split('='); if (temp[0] === key) { cookieValue = temp[1]; break } } return cookieValue };Copy the code

Cookies are deleted

/** * @param {String} key attribute */ export const cookieRemove = (key) => {document.cookie = '${encodeURIComponent(key)}=; expires=${new Date()}` };Copy the code

More utility functions

This contains the usual utility functions, including numbers, strings, arrays, objects and so on.

Money format, three digits plus comma

/** * @param { number } num */ export const formatMoney = num => num.toString().replace(/\B(? =(\d{3})+(? ! \d))/g, ",");Copy the code

Truncate the string and omit it

export function subText(str, length) {
    if (str.length === 0) {
        return '';
    }
    if (str.length > length) {
        return str.substr(0, length) + "...";
    } else {
        return str;
    }
}Copy the code

Get the base64 encoding of the file

/** * @param file * @param format Specifies the file format * @param size specifies the file size (bytes) * @param formatMsg format error message * @param sizeMsg size out of limit message * @returns {Promise<any>} */ export function fileToBase64String(file, format = ['jpg', 'jpeg', 'png', 'gif'], Size = 20 * 1024 * 1024, formatMsg = 'sizeMsg ', sizeMsg =' sizeMsg ') {return new Promise((resolve, Reject) => {// let suffix = file.type.split('/')[1].tolowerCase (); let inFormat = false; for (let i = 0; i < format.length; i++) { if (suffix === format[i]) { inFormat = true; break; } } if (! inFormat) { reject(formatMsg); Size > size) {reject(reject(sizeMsg); } // base64 let fileReader = new fileReader (); fileReader.readAsDataURL(file); fileReader.onload = () => { let res = fileReader.result; resolve({base64String: res, suffix: suffix}); Reject (' Abnormal file, please select again '); }})}Copy the code

B converts to KB,MB,GB and keeps two decimal places

/** * @param { number } fileSize */ export function formatFileSize(fileSize) { let temp; if (fileSize < 1024) { return fileSize + 'B'; } else if (fileSize < (1024 * 1024)) { temp = fileSize / 1024; temp = temp.toFixed(2); return temp + 'KB'; } else if (fileSize < (1024 * 1024 * 1024)) { temp = fileSize / (1024 * 1024); temp = temp.toFixed(2); return temp + 'MB'; } else { temp = fileSize / (1024 * 1024 * 1024); temp = temp.toFixed(2); return temp + 'GB'; }}Copy the code

Base64 transfer the file

/** * @param {base64} base64 * @param {string} filename */ export const base64ToFile = (base64, filename )=> { let arr = base64.split(','); let mime = arr[0].match(/:(.*?) ; / [1]); let suffix = mime.split('/')[1] ; Let BSTR = atob(arr[1]); let n = bstr.length; let u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new File([u8arr], `${filename}.${suffix}`, { type: mime }) };Copy the code

Turn base64 blob

/** * @param { base64 } base64 */ export const base64ToBlob = base64 => { let arr = base64.split(','), mime = arr[0].match(/:(.*?) ; /)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); };Copy the code

Turn a blob file

/**
 *  @param { blob } blob
 *  @param { string } fileName
 */
export const blobToFile = (blob, fileName) => {
    blob.lastModifiedDate = new Date();
    blob.name = fileName;
    return blob;
};Copy the code

The file transfer base64

/** * @param {*} file */ export const fileToBase64 = file => {let reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { return e.target.result }; };Copy the code

Recursively generates a tree structure

export function getTreeData(data, pid, pidName = 'parentId', idName = 'id', childrenName = 'children', key) {
    let arr = [];

    for (let i = 0; i < data.length; i++) {
        if (data[i][pidName] == pid) {
            data[i].key = data[i][idName];
            data[i][childrenName] = getTreeData(data, data[i][idName], pidName, idName, childrenName);
            arr.push(data[i]);
        }
    }

    return arr;
}Copy the code

Walk through the tree nodes

export function foreachTree(data, childrenName = 'children', callback) { for (let i = 0; i < data.length; i++) { callback(data[i]); if (data[i][childrenName] && data[i][childrenName].length > 0) { foreachTree(data[i][childrenName], childrenName, callback); }}}Copy the code

Trace parent node

export function traceParentNode(pid, data, rootPid, pidName = 'parentId', idName = 'id', childrenName = 'children') { let arr = []; foreachTree(data, childrenName, (node) => { if (node[idName] == pid) { arr.push(node); if (node[pidName] ! = rootPid) { arr = arr.concat(traceParentNode(node[pidName], data, rootPid, pidName, idName)); }}}); return arr; }Copy the code

Find all child nodes

export function traceChildNode(id, data, pidName = 'parentId', idName = 'id', childrenName = 'children') {
    let arr = [];
    foreachTree(data, childrenName, (node) => {
        if (node[pidName] == id) {
            arr.push(node);
            arr = arr.concat(traceChildNode(node[idName], data, pidName, idName, childrenName));
        }
    });
    return arr;
}Copy the code

Generate tree structure according to PID

/** * @param {object} items Data obtained in the background * @param {*} ID ID in the data * @param {*} link Basis for generating the tree structure */ export const createTree = (items, id = null, link = 'pid') =>{ items.filter(item => item[link] === id).map(item => ({ ... item, children: createTree(items, item.id) })); };Copy the code

Queries for the presence of an element in an array and returns the index of the element’s first occurrence

/** 
 * @param {*} item 
 * @param { array } data
 */
export function inArray(item, data) {
    for (let i = 0; i < data.length; i++) {
        if (item === data[i]) {
            return i;
        }
    }
    return -1;
}Copy the code

Windows Determines the current system name based on the detailed version number

/** * @param { string } osVersion */ export function OutOsName(osVersion) { if(! osVersion){ return } let str = osVersion.substr(0, 3); If (STR === "5.0") {return "Win 2000"} else if (STR === "5.1") {return "Win XP"} else if (STR === "5.2") {return "Win XP64"} else if (STR === "6.0") {return "Win Vista"} else if (STR === "6.1") {return "Win 7"} else if (STR === = "6.1") "6.2") {return "Win 8"} else if (STR === "6.3") {return "Win 8.1"} else if (STR === "10.") {return "Win 10"} else { return "Win" } }Copy the code

Determine if your phone is Android or IOS

/** * 0: ios * 1: android * 2: Export function getOSType() {let u = navigator.userAgent, app = navigator.appversion; let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; let isIOS = !! u.match(/\(i[^;] +; ( U;) ? CPU.+Mac OS X/); if (isIOS) { return 0; } if (isAndroid) { return 1; } return 2; }Copy the code

Function image stabilization

/** * @param {function} func * @param {number} wait number of milliseconds * @param {Boolean} immediate true */ export function debounce(func,wait,immediate) {let timeout; return function () { let context = this; let args = arguments; if (timeout) clearTimeout(timeout); if (immediate) { let callNow = ! timeout; timeout = setTimeout(() => { timeout = null; }, wait); if (callNow) func.apply(context, args) } else { timeout = setTimeout(() => { func.apply(context, args) }, wait); }}}Copy the code

Function of the throttle

/** * @param {function} func function * @param {number} wait * @param {number} type 1 */ export function throttle(func, wait,type) {let previous, timeout; if(type===1){ previous = 0; }else if(type===2){ timeout = null; } return function() { let context = this; let args = arguments; if(type===1){ let now = Date.now(); if (now - previous > wait) { func.apply(context, args); previous = now; } }else if(type===2){ if (! timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } } }Copy the code

Determine the data type

/** * @param {*} target */ export function type(target) { let ret = typeof(target); let template = { "[object Array]": "array", "[object Object]":"object", "[object Number]":"number - object", "[object Boolean]":"boolean - object", "[object String]":'string-object' }; if(target === null) { return 'null'; }else if(ret == "object"){ let str = Object.prototype.toString.call(target); return template[str]; }else{ return ret; }}Copy the code

Generates a range of random numbers

/**
 * @param { number } min 
 * @param { number } max 
 */
export const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;Copy the code

An array of random sequence

/**
 * @param {array} arr
 */
export function arrScrambling(arr) {
    let array = arr;
    let index = array.length;
    while (index) {
        index -= 1;
        let randomIndex = Math.floor(Math.random() * index);
        let middleware = array[index];
        array[index] = array[randomIndex];
        array[randomIndex] = middleware
    }
    return array
}Copy the code

An array of overlap

/**
 * @param { array} arr1
 * @param { array } arr2
 */
export const similarity = (arr1, arr2) => arr1.filter(v => arr2.includes(v));Copy the code

The number of occurrences of an element in an array

/**
 * @param { array } arr
 * @param {*} value
 */
export function countOccurrences(arr, value) {
    return arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
}Copy the code

Addition function (precision loss problem)

/** * @param { number } arg1 * @param { number } arg2 */ export function add(arg1, arg2) { let r1, r2, m; try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 } try { r2 = arg2.toString().split(".")[1].length }  catch (e) { r2 = 0 } m = Math.pow(10, Math.max(r1, r2)); return (arg1 * m + arg2 * m) / m }Copy the code

Subtraction function (precision loss problem)

/** * @param { number } arg1 * @param { number } arg2 */ export function sub(arg1, arg2) { let r1, r2, m, n; try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 } try { r2 = arg2.toString().split(".")[1].length }  catch (e) { r2 = 0 } m = Math.pow(10, Math.max(r1, r2)); n = (r1 >= r2) ? r1 : r2; return Number(((arg1 * m - arg2 * m) / m).toFixed(n)); }Copy the code

Division function (precision loss problem)

/**
 * @param { number } num1
 * @param { number } num2
 */
export function division(num1,num2){
    let t1,t2,r1,r2;
    try{
        t1 = num1.toString().split('.')[1].length;
    }catch(e){
        t1 = 0;
    }
    try{
        t2=num2.toString().split(".")[1].length;
    }catch(e){
        t2=0;
    }
    r1=Number(num1.toString().replace(".",""));
    r2=Number(num2.toString().replace(".",""));
    return (r1/r2)*Math.pow(10,t2-t1);
}Copy the code

Multiplication function (precision loss problem)

/**
 * @param { number } num1
 * @param { number } num2
 */
export function mcl(num1,num2){
    let m=0,s1=num1.toString(),s2=num2.toString();
    try{m+=s1.split(".")[1].length}catch(e){}
    try{m+=s2.split(".")[1].length}catch(e){}
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
}Copy the code

Recursive optimization (tail recursion)

/**
 * @param { function } f
 */
export function tco(f) {
    let value;
    let active = false;
    let accumulated = [];

    return function accumulator() {
        accumulated.push(arguments);
        if (!active) {
            active = true;
            while (accumulated.length) {
                value = f.apply(this, accumulated.shift());
            }
            active = false;
            return value;
        }
    };
}Copy the code

Generating random integers

export function randomNumInteger(min, max) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * min + 1, 10);
        case 2:
            return parseInt(Math.random() * (max - min + 1) + min, 10);
        default:
            return 0
    }
}Copy the code

Remove the blank space

/** * @param {string} STR String to be processed * @param {number} type Remove space type 1- All Spaces 2- Before and after Spaces 3- Before and after Spaces 4- After Spaces The default is 1 */ export function trim(str, type = 1) { if (type && type ! == 1 && type ! == 2 && type ! == 3 && type ! == 4) return; 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; }}Copy the code

Case conversion

/** * @param {string} STR String to be converted * @param {number} type 1- All uppercase 2- All lowercase 3- Uppercase other - No conversion */ export function turnCase(STR,  type) { switch (type) { case 1: return str.toUpperCase(); case 2: return str.toLowerCase(); case 3: return str[0].toUpperCase() + str.substr(1).toLowerCase(); default: return str; }}Copy the code

Random hexadecimal color hexColor

/** * export function hexColor() {let STR = '#'; let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']; for (let i = 0; i < 6; i++) { let index = Number.parseInt((Math.random() * 16).toString()); str += arr[index] } return str; }Copy the code

Random hexadecimal color randomHexColorCode

/** * export const randomHexColorCode = () => {let n = (math.random () * 0xfffff * 1000000).toString(16); return '#' + n.slice(0, 6); };Copy the code

Escape HTML (against XSS attacks)

export const escapeHTML = str =>{ str.replace( /[&<>'"]/g, tag => ({ '&': '&amp; ', '<': '&lt; ', '>': '&gt; ', '" : "& # 39; ', '"': '&quot; ' }[tag] || tag) ); };Copy the code

Detect mobile /PC devices

export const detectDeviceType = () => { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop'; };Copy the code

Hides all specified labels

/ * * * example: hide (document. QuerySelectorAll (' img)) * / export const hideTag = (... el) => [...el].forEach(e => (e.style.display = 'none'));Copy the code

Returns the effective style of the specified element

/** * @param {element} el element node * @param {string} ruleName export const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];Copy the code

Check whether child elements are included

/** * @param {element} parent * @param {element} child elementContains(document.querySelector('head'), document.querySelector('title')); // true */ export const elementContains = (parent, child) => parent ! == child && parent.contains(child);Copy the code

If the number exceeds the specified size plus the plus sign “+”, if the number exceeds 99, 99+ is displayed

/** * @param {number} val /* @param {number} maxNum / / export const outOfNum = (val, maxNum) =>{ val = val ? val-0 :0; if (val > maxNum ) { return `${maxNum}+` }else{ return val; }};Copy the code

To be continued…

reference

Github.com/any86/any-…. juejin.cn/post/1… juejin.cn/post/1… juejin.cn/post/1… juejin.cn/post/1…

The last

The above tool function, part from their usual summary, part from the above reference article, thank the gods summary. If it helps, click star on GitHub to check it out

This repository will be updated continuously, if you have better ideas, or don’t find the tool functions you want, welcome issues~

If there are inaccuracies or errors in the article, please point them out