20 methods that programmers must collect

Posted May 25, 20205 min read

The editor has recently sorted out some frequently used methods of the front end to facilitate the use in later projects. These are the methods often used in the project. Share them with your friends. Remember to click collection, follow, and like ~

image.png

  1. Mailbox

    export const isEmail =(s) => {

     return/^([a-zA-Z0-9 _-]) + @([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. Phone number

    export const isPhone =(s) => {

     return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)

    }

  4. Whether the string

    export const isString =(o) => {

     return Object.prototype.toString.call(o) .slice(8, -1) === 'String'

    }

  5. Whether the number

    export const isNumber =(o) => {

     return Object.prototype.toString.call(o) .slice(8, -1) === 'Number'

    }

  6. Download according to 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;

    }

  7. 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 wrong')
         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 ", 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:" Macau ", 91:" Overseas "};
     if(! aCity [parseInt(sId.substr(0, 2))]) {
         console.log('Your ID 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 date of birth on ID')
         return false
     }
    
     //ID card 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('Illegal ID number you entered')
         return false
     }
    
     return true

    }

  8. Array sort, {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;
         }
     })

    }

  9. Deduplication

    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;
     }

    }

  10. Delete one of the elements

    export const remove =(arr, ele) => {

    var index = arr.indexOf(ele);
    if(index> -1) {
        arr.splice(index, 1);
    }
    return arr;

    }

  11. Character conversion, `type:1:Capitalization of the first letter 2:Capitalization of the first letter 3:Capitalization conversion 4:All uppercase 5:All lowercase

    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;
    }

    }

  12. Maximum

    export const max =(arr) => {

    return Math.max.apply(null, arr);

    }

  13. Minimum

    export const min =(arr) => {

    return Math.min.apply(null, arr);

    }

  14. Summation

    export const sum =(arr) => {

    return arr.reduce((pre, cur) => {
        return pre + cur
    })

    }

  15. Average

    export const average =(arr) => {

    return this.sum(arr)/arr.length

    }

  16. Remove spaces, type:1- all spaces 2- before and after spaces 3- before spaces 4- after 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;
    }

    }

  17. 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;

    }

  18. Determine whether an element is in an array

    export const contains =(arr, val) => {

    return arr.indexOf(val)! = -1? true:false;

    }

  19. 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];

    }

  20. Judgment 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'://Landline
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
        case 'card'://ID
            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, and can only contain letters, numbers and underscores
            return /^[a-zA-Z]\w{5,17}$/.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'://mailbox
            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 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'://lowercase
            return /^[a-z]+$/.test(str);
        case 'upper'://Capital
            return /^[A-Z]+$/.test(str);
        case 'HTML'://HTML tags
            return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
        default:
            return true;
    }

    }

Editor is not easy, if there is any harvest, WeChat rewards editor to drink Wahaha

image.png

Single dog's sunflower collection, a must-have for sisters, stay tuned!
image.png