digital

To a random integer in a certain range

function randomIntegerInRange(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
Copy the code

Determine if the number is odd

function isEven(num) {
    return num % 2= = =0;
}
Copy the code

Intercept the decimal point (not round)

function toFixed(value, fixed) {
    return~ ~ (Math.pow(10, fixed) * value) / Math.pow(10, fixed);
}

console.log(toFixed(1.123456789.0)); / / 1
console.log(toFixed(1.123456789.1)); / / 1.1
console.log(toFixed(1.123456789.2)); / / 1.12
console.log(toFixed(1.123456789.3)); / / 1.123
console.log(toFixed(1.123456789.4)); / / 1.1234
console.log(toFixed(1.123456789.5)); / / 1.12345
Copy the code

Verify numbers, which can contain a minus sign and a decimal point

function isNumber(number) {
    if(! number && number ! =0) {
        console.error('Please enter the number you want to validate');
        return;
    }
    let regex = / ^ -? \d+$|^(-? \d+)(\.\d+)? $/;
    if (number.toString().match(regex)) {
        return true;
    } else {
        return false; }}Copy the code

Validates integers, which can contain negative integers

function isInteger(integer){
  if(! integer && integer ! =0) {
    console.error('Please enter an integer to validate');
    return;
  }
  let regex = / ^ -? \d+$/;
  if (integer.toString().match(regex)) {
    return true;
  } else {
    return false; }}Copy the code

Verify the decimal

function isDecimal(decimal) {
  if(! decimal) {console.error('Please enter the decimal number you want to validate');
    return;
  }
  let regex = / ^ ([+]? [1-9]\d*\.\d+|-? 0\.\d*[1-9]\d*)$/;
  if (decimal.toString().match(regex)) {
    return true;
  } else {
    return false; }}Copy the code

Boolean

A random Boolean value

function randomBoolean() {
    return Math.random() >= 0.5;
}
Copy the code

string

Capitalize the first letter of each word

function capitalizeEveryWord(str) {
    return str.replace(/\b[a-z]/g.char= > char.toUpperCase());
}
Copy the code

Invert a string

Methods a

function reverseString(str){
    return [...str].reverse().join(' ');
}
Copy the code

Way 2

function reverseString(str) {
    return str.split(' ').reverse().join(' ');
}
Copy the code

Sort the string alphabetically, returning the sorted string

function sortCharactersInString(str) {
    return str.split(' ').sort((a, b) = > a.localeCompare(b)).join(' ');
}
Copy the code

Removes consecutive characters from a string

function uniq(str) {
    return str.replace(/(\w)\1+/g.'$1')}Copy the code

Delete Spaces at both ends of the string

function trim(string) {
    return (string || ' ').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g.' ');
}
Copy the code

ECMAScript5 also provides the trim() method for strings.

var str = 'Orange someone';
console.log(str.trim()); / / orange someone

If your browser does not support the trim() method, however, you can do this with regular expressions.
Copy the code

Looks for the first occurrence of a letter in a string only once

function firstAppear(str) {
    var obj = {},
        len = str.length;
    for (var i = 0; i < len; i++) {
        if (obj[str[i]]) {
            obj[str[i]]++;
        } else {
            obj[str[i]] = 1; }}for (var prop in obj) {
       if (obj[prop] == 1) {
         returnprop; }}}console.log(firstAppear('aabbcddfee')); // c
console.log(firstAppear('aabbccddfee')); // f
Copy the code

Checks if the string is palindrome

Methods a

function isPalina(str) {
    if (Object.prototype.toString.call(str) ! = ='[object String]') {
        return false;
    }
    var len = str.length;
    for (var i = 0; i < len / 2; i++) {
        if(str[i] ! = str[len -1 - i]) {
            return false; }}return true;
}
Copy the code

Way 2

function isPalindrome(str) {
    str = str.replace(/\W/g.' ').toLowerCase();
    return (str == str.split(' ').reverse().join(' '));
}
Copy the code

Gets the parameters in the URL

function getUrlParams(url) {
    var args = url.split('? ');
    if (args[0] === url) return ({});
    var hrefarr = args[1].split(The '#') [0].split('&');
    var obj = {};
    for (var i = 0; i < hrefarr.length; i++) {
        hrefarr[i] = hrefarr[i].split('=');
        if(hrefarr[i][0]) 
            obj[hrefarr[i][0]] = hrefarr[i][1];
    }
    return obj;
}
Copy the code

Extract the img tag to get SRC

function getImgEleSrc(imgEle = ' ') {
    return imgEle.match(/src=[\'\"]? ([^] *) [\ '\' \ '\]?" /i) [1];
}

console.log(getImgEleSrc('<img src="https://juejin.cn/" alt="" />')); // https://juejin.cn/
Copy the code

Filtering special Characters

/ * * *@param STR: indicates the character * to be filtered@param Rule: user-defined special characters *@param Append: appends the filtered special character * to the default special character@returns String: the filtered character */
function filterStr(str, rule, append) {
    if(! rule) rule ="[` ~! @ # $^ & * () = | {} ':', \ \ [\ \] < > /? ~! @ # $... & * () - | {} 【 】 '; :" "'.,,? ";
    if(append) rule = rule.slice(0.1) + append + rule.slice(1);
    let pattern = new RegExp(rule);
    let retrunStr = ' ';
    for (let i = 0; i < str.length; i++){ retrunStr = retrunStr + str.substr(i,1).replace(pattern, ' ');
    }
    return retrunStr;
}
Copy the code

Intercepts a string of the specified length

/ * * *@description Truncate character *@type {{func: truncate.func}} * /
function truncate(value, length) {
    if(! value)return value;
    if(value.length <= length) return value;
    return value.slice(0, length) + '... ';
}
Copy the code

An array of

Check if it is an array

function isArray(arr) {
    return arr instanceof Array;
}
// or
function isArray(arr) {
    return Array.isArray(arr);
}
Copy the code

When detecting Array instances, array. isArray is superior to instanceof because array. isArray can detect iframes.

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var iArray = window.frames[window.frames.length-1].Array;
var arr = new iArray(1.2.3); / / [1, 2, 3]
console.log(Array.isArray(arr)); // true
console.log(arr instanceof Array); // false
Copy the code

Summation of arrays

/ * * *@param Arr: The value can be an integer, decimal, or digit string */
function arraySum(arr) {
    return arr.reduce((acc, val) = > parseFloat(acc) + parseFloat(val), 0);
}
Copy the code

Randomly shuffled array to sort, return the shuffled array

function randomizeOrder(arr) {
    return arr.sort((a, b) = > Math.random() >= 0.5 ? -1 : 1)}Copy the code

Array to heavy

Methods a

function arrayDuplicateRemoval(arr) {
    return [...new Set(arr)];
}
Copy the code

Way 2

function arrayDuplicateRemoval(arr) {
    var obj = {};
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        if(! obj[arr[i]]) { obj[arr[i]] =true;
            result.push(arr[i])
        }
    }
    return result;
}
Copy the code

Methods three

function arrayDuplicateRemoval(arr) {
    var obj = {};
    return arr.filter(ele= > {
        if(! obj[ele]) { obj[ele] =true;
            return true; }})}Copy the code

Methods four

function arrayDuplicateRemoval(arr) {
    var result = [];
    arr.forEach(ele= > {
        if (result.indexOf(ele) == -1) {
            result.push(ele)
        }
    })
    return result;
}
Copy the code

object

Check if it is an object

function isObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]';
}
Copy the code

Clears the value of an object

/ * * *@ignoreKey Array or String: Ignore some keys and do not empty */
function clearEmptyObject(object, ignoreKey) {
    if(typeofobject ! = ='object') return;
    for(let key in object) {
      if(Object.prototype.toString.call(object[key]) === '[object Object]') {
        clearEmptyObject(object[key]);
      }
      else {
        if(ignoreKey && (
          (typeof ignoreKey === 'string' && ignoreKey === key) ||
          (ignoreKey instanceof Array && ignoreKey.includes(key))
        )) return;
        if(Array.isArray(object[key])) {
          object[key] = [];
        }else {
          if(typeof object[key] === 'boolean') {
            object[key] = false;
          }else {
            object[key] = ' ';
          }
        }
      }
    }
}
Copy the code

The date of

Check if it is a valid date

/ * * *@method Check if it is a valid date *@param Date is the converted value */
function isValidDate(date) {
  return date instanceof Date&&!isNaN(date.getTime())
}
Copy the code

Determine how many days a month has

/ * * *@method Gets the number of days in a month *@param Year years *@param Month Month (e.g. 2) */
function getDaysInMonth(year, month) {
  return new Date(year, month, 0).getDate()
}
Copy the code

Judge the interpolation of days between two dates

/ * * *@method Determine the difference in days between two dates *@param {*} EndDate endDate the value is in the format of 2018-01-01 *@param {*} StartDate startDate the date is a string in the format of 2018-01-01 */
function DateDifference (endDate, startDate) {
  return parseInt((Math.abs(new Date(endDate) - new Date(startDate)) / 1000 / 60 / 60 / 24) + 1)}Copy the code

Various date conversion formats

function dateChangeFormat(date = new Date(), format = 'yyyy-MM-dd', char = The '-') {
    if(! (dateinstanceof Date)) {
      date = new Date(date);
    }
    let YYYY = date.getFullYear();
    let MM = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1);
    let DD = date.getDate() > 9 ? date.getDate() : '0' + date.getDate();
    let hh = date.getHours() > 9 ? date.getHours() : '0' + date.getHours();
    let mm = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes();
    let ss = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds();
    switch (format) {
      case 'yyyy-MM-dd': return `${YYYY}${char}${MM}${char}${DD}`;break;
      case 'yyyy-MM-dd hh:mm:ss': return `${YYYY}${char}${MM}${char}${DD} ${hh}:${mm}:${ss}`; break;
      case 'text': return `${YYYY}years${MM}month${DD}Day `;break;
      case 'text hh:mm:ss': return `${YYYY}years${MM}month${DD}day${hh}:${mm}:${ss}`;break;
      case 'empty': return `${YYYY}${MM}${DD}${hh}${mm}${ss}`;break; }}Copy the code

More other formats, add a case directly.

Check whether the date is a working day

function isWeekday(date) {
    return date.getDay() % 6! = =0;
}
Copy the code

Determine whether a time is between two times

/ * * *@method Determine whether a time is between two times *@param SDate1 and sDate2 indicate the date, for example, 2019-01-01 */
function dateBetweenJudget(startDate, endDate, date) {
  let oStartDate = new Date(startDate)
  let oEndDate = new Date(endDate)
  let oDate = new Date(date)
  if ((oEndDate.getTime() >= oDate.getTime()) && (oStartDate.getTime() <= oDate.getTime())) {
    return true
  }
  return false
}
Copy the code

Compare two time sizes

/ * * *@param Date1: date type or YYYY-MM-DD; Benchmark *@param Date2: indicates the date type or YYYY-MM-DD. The default compares to the current date *@param CompareTime: whether to compare the time *@returns boolean1 0 1 * /
function compareDate(date1, date2 = new Date(), compareTime = false){
    let flag = null;
    if(! date1) {console.warn('Please enter the date of comparison');
      return;
    }
    if(! (date1instanceof Date)) {
      date1 = new Date(date1.replace(/-/g."/ /"));
    }
    if(! (date2instanceof Date)) {
      date2 = new Date(date2.replace(/-/g."/ /"));
    }
    // Do not compare time, only compare date
    if(! compareTime) { date1 =new Date(date1.getFullYear() + '/' + (date1.getMonth()+1) + '/' + date1.getDate());
      date2 = new Date(date2.getFullYear() + '/' + (date2.getMonth()+1) + '/' + date2.getDate());
    }
    if(date1.getTime() < date2.getTime()){
      flag =  -1;
    }else if(date1.getTime() == date2.getTime()) {
      flag =  0;
    }else {
      flag =  1;
    }
    return flag;
}
Copy the code

Gets all the days of a month

function getMonthAllDays(year, month) {
    let monthData = [];
    // Initial default value
    if(! year || ! month) { year =new Date().getFullYear();
      month = new Date().getMonth() + 1;
    }
  
    // Get the first day of the month and the day of the week
    let curMonthFirstDay = new Date(year, month - 1.1);
    let curMonthFirstDayWeek = curMonthFirstDay.getDay() === 0 ? 7 : curMonthFirstDay.getDay();
    year = curMonthFirstDay.getFullYear();
    month = curMonthFirstDay.getMonth() + 1;
  
    // Get the last day of the month and the date
    let curMonthLastDay = new Date(year, month, 0);
    let curMonthLastDayNum = curMonthLastDay.getDate();
  
    // Get the last day of the last month and the date
    let prevMonthLastDay = new Date(year, month - 1.0); // month-1: specifies the original month. 0: specifies the last day of a month
    let prevMonthLastDayNum = prevMonthLastDay.getDate();
  
    // Calculate the number of days for the last month
    let prevMonthDayCount = curMonthFirstDayWeek - 1; // If the first day of this month is Thursday, then 4-1 = 3
  
    for (let i = 0; i < 7 * 6; i++){
      let date = i - prevMonthDayCount;
      let showDay = date;
      let showMonth = month;
      let showYear = year;
  
      // The number of days is out of bounds
      if (date <= 0) {
        // Last month
        showDay = prevMonthLastDayNum + date;
        showMonth = month - 1;
      }
      else if (date > curMonthLastDayNum) {
        / / next month
        showDay = showDay - curMonthLastDayNum;
        showMonth = month + 1;
      }
  
      // The number of months is out of bounds
      if (showMonth <= 0) showMonth = 12;
      if (showMonth > 12) showMonth = 1;
  
      // The number of years is out of bounds
      if(month === 12 && showMonth === 1) showYear = year + 1;
      if(month === 1 && showMonth === 12) showYear = year - 1;
  
      monthData.push({
        showYear,
        showMonth,
        showDay,
        date,
        isCurrentDay: compareDate(showYear + '/' + showMonth + '/' + showDay), // Use the compareDate function above to compare two dates
        isSaturday: new Date(showYear + '/' + showMonth + '/' + showDay).getDay() === 6 ? 1 : 0.isSunday: new Date(showYear + '/' + showMonth + '/' + showDay).getDay() === 0 ? 1 : 0})}return {
      year,
      month,
      days: monthData
    }
}
Copy the code

Dom

Check whether class exists

/ * * *@param El: Dom element *@param CLS: multiple Spaces separated by */
function hasClass(el, cls) {
    if(! el || ! cls)return false;
    if (cls.indexOf(' ')! = = -1) throw new Error('className should not contain space.');
    if (el.classList) {
      return el.classList.contains(cls);
    } else {
      return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1; }}Copy the code

To add a class

/ * * *@param El: Dom element *@param CLS: multiple Spaces separated by */
function addClass(el, cls) {
    if(! el)return;
    var curClass = el.className;
    var classes = (cls || ' ').split(' ');
    for(var i = 0, j = classes.length; i < j; i++) {
      var clsName = classes[i];
      if(! clsName)continue;
      if (el.classList) {
        el.classList.add(clsName);
      } else if (hasClass(el, clsName)) { // The above hasClass method is called
        curClass += ' '+ clsName; }}if (!el.classList) {
      el.className = curClass;
    }
}
Copy the code

Remove the class

/ * * *@param El: Dom element *@param CLS: multiple Spaces separated by */
function removeClass(el, cls) {
    if(! el || ! cls)return;
    var classes = cls.split(' ');
    var curClass = ' ' + el.className + ' ';
    for (var i = 0, j = classes.length; i < j; i++) {
        var clsName = classes[i];
        if(! clsName)continue;
        if (el.classList) {
            el.classList.remove(clsName);
        } else if (hasClass(el, clsName)) { // The above hasClass method is called
            curClass = curClass.replace(' ' + clsName + ' '.' '); }}if(! el.classList) { el.className = (curClass ||' ').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g.' '); }}Copy the code

The browser

Check whether the current Tab page is visible

function isBrowserTabInView() {
    return document.hidden;
}
Copy the code

Determines whether an element is currently in the focus state

The Document. activeElement API is supported by all browsers

function elementIsInFocus(el) {
    return el === document.activeElement;
}
Copy the code

Determine whether the browser supports touch events

Return true is supported. Return undefined is not supported

function touchSupported() {
    return ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
Copy the code

Scroll to the top of the page

The window.scrollto () method takes an X and y coordinate to scroll through. The scrollTo() method is not supported by IE.

function goToPageTop() {
    return window.scrollTo(0.0);
}
Copy the code

Determines if an element has children

function hasChildren(e) {
    var children = e.childNodes;
    var len = children.length;
    for(var i = 0; i < len; i++) {
        if (children[i].nodeType === 1) {
            return true; }}return false;
}
Copy the code

Gets the scroll distance of the scroll bar

function getScrollOffset() {
    if (window.pageXOffset) {
        return {
            x: window.pageXOffset,
            y: window.pageYOffset
        }
    } else {
        return {
            x: document.body.scrollLeft + document.documentElement.scrollLeft,
            y: document.body.scrollTop + document.documentElement.scrollTop
        }
    }
}
Copy the code

Get the viewport dimensions

function getViewportOffset() {
    if (window.innerWidth) {
        return {
            w: window.innerWidth,
            h: window.innerHeight
        }
    } else {
        // Ie8 and below
        if (document.compatMode === "BackCompat") {
            // Weird mode
            return {
                w: document.body.clientWidth,
                h: document.body.clientHeight
            }
        } else {
            // Standard mode
            return {
                w: document.documentElement.clientWidth,
                h: document.documentElement.clientHeight
            }
        }
    }
}
Copy the code

Cancels bubbling compatibility code

function stopBubble(e) {
    if (e && e.stopPropagation) {
        e.stopPropagation();
    } else {
        window.event.cancelBubble = true; }}Copy the code

other

Check that the value is null

function isEmpty(val) {
    if (val === 0) return false;
    // null or undefined
    if (val == null) return true;
    if (typeof val === 'boolean') return false;
    if (typeof val === 'number') return! val;if (val instanceof Error) return val.message === ' ';
    switch (Object.prototype.toString.call(val)) {
      // String or Array
      case '[object String]':
      case '[object Array]':
        return! val.length;// Map or Set or File
      case '[object File]':
      case '[object Map]':
      case '[object Set]': {
        return! val.size; }// Plain Object
      case '[object Object]': {
        return !Object.keys(val).length; }}return false;
}
Copy the code

Enter a value and return its data type

function type(value) {
    return Object.prototype.toString.call(value);
}

var typeMaps = [1.'1'.true.null.undefined, {}, [], () = > {}, new Date()];
typeMaps.forEach(value= > console.log(type(value)));
/* Result [object Number] [object String] [object Boolean] [object Null] [object Undefined] [object object] [object Array] [object Function] [object Date] */ 

Copy the code

RGB to hexadecimal

function rgbToHex(r, g, b){
    return The '#' + ((r << 16) + (g << 8) + b).toString(16).padStart(6.'0');
}

console.log(rgbToHex(255.255.255)); // #ffffff
console.log(rgbToHex(0.0.0)); / / # 000000
Copy the code

Deep copy

Methods a

Json.parse () and json.stringify () are simple and crude, but elements can only be objects or arrays, and other types such as functions, dates, and so on are problematic.

function deepCopy(obj) {
    return JSON.parse(JSON.stringify(obj));
}

let arr = [() = > {}, { b: () = >{}},new Date()];
let newArr = JSON.parse(JSON.stringify(arr));
console.log(newArr);

let obj = {a: () = > {}, b: new Date(a)};let newObj = JSON.parse(JSON.stringify(obj));
console.log(newObj);
Copy the code

The function disappears entirely, and the date type becomes a string.

Way 2

Recursively, specific judgments need to be added for other types of elements.

function deepCopy(obj) {
  if (typeofobj ! = ='object') return;
  let result = obj instanceof Array ? [] : {};
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      result[key] = typeof obj[key] === 'object' && !(obj[key] instanceof Date)? deepCopy(obj[key]) : obj[key]; }}return result;
}
Copy the code

Get star

function getLevel(rate) {
    return Painted "u u u u being fostered fostered fostered fostered".slice(5 - rate, 10 - rate);
}
Copy the code

Image stabilization function

function debounce(fn, delay = 500) {
  let timer = null;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() = > {
      fn.apply(this.arguments);
    }, delay);
  };
}
Copy the code

Throttling function

function throttle(fn, gapTime) {
  let _lastTime = null;

  return function () {
    let _nowTime = + new Date(a)if(_nowTime - _lastTime > gapTime || ! _lastTime) { fn(); _lastTime = _nowTime } } }Copy the code

Landline or cell phone number

function isTelePhoneNumber(phone) {
  if(! phone) {console.error('Please enter the landline or mobile number you want to authenticate');
    return;
  }
  let reg = ,4,5,6,7,8 / ^ [1] [3] [0-9] {9} $| ^ 0 \ d {2, 3} -? \ d {7, 8} $/;
  if (phone.toString().match(reg)) {
    return true;
  } else {
    return false; }}Copy the code

Verify mobile phone number

function isPhoneNumber(phone) {
  if(! phone) {console.error('Please enter the mobile phone number you want to verify');
    return;
  }
  let reg = ,4,5,6,7,8,9 / ^ [1] [3] [0-9] {9} $/;
  if (phone.toString().match(reg)) {
    return true;
  } else {
    return false; }}Copy the code

Verify the tax code, 15 or 17 or 18 or 20 letters, digits

function isCheckTax(tax) {
  if(! tax) {console.error('Please enter the tax code to be verified');
    return;
  }
  let reg = /^[A-Z0-9]{15}$|^[A-Z0-9]{17}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$/;
  if (tax.toString().match(reg)) {
    return true;
  } else {
    return false; }}Copy the code

Verified ID number, which can verify the first or second generation ID card

function isIdCard(input) {
  if(! input) {console.error('Please enter the id number you want to authenticate');
    return;
  }
  input = input.toUpperCase();
  // Verify the id card number format, the first-generation ID card number is 15 digits; The second generation id card number is 18 digits or 17 digits plus the letter X
  if(! (/(^\d{15}$)|(^\d{17}([0-9]|X)$)/i.test(input))) {
    return false;
  }
  // Verify the province
  let arrCity = {
    11: 'Beijing'.12: 'tianjin'.13: 'hebei'.14: 'the shanxi'.15: Inner Mongolia.21: 'the liaoning'.22: 'jilin'.23: 'Heilongjiang'.31: 'Shanghai'.32: 'jiangsu'.33: 'zhejiang'.34: 'anhui'.35: 'fujian'.36: 'jiangxi'.37: 'shandong'.41: 'henan'.42: 'hubei'.43: 'in hunan province'.44: 'in guangdong'.45: 'the guangxi'.46: 'hainan'.50: 'chongqing'.51: 'sichuan'.52: 'guizhou'.53: 'yunnan'.54: 'Tibet'.61: 'the shaanxi'.62: 'gansu'.63: 'the qinghai'.64: 'the ningxia'.65: 'the xinjiang'.71: 'Taiwan'.81: 'Hong Kong'.82: 'the'.91: 'foreign'
  };
  if(arrCity[parseInt(input.substr(0.2= =))]null) {
    return false;
  }
  // Verify birth date
  let regBirth, birthSplit, birth;
  let len = input.length;
  if(len == 15) {
    regBirth = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
    birthSplit = input.match(regBirth);
    birth = new Date('the' + birthSplit[2] + '/' + birthSplit[3] + '/' + birthSplit[4]);
    if(! (birth.getYear() ==Number(birthSplit[2]) && (birth.getMonth() + 1) = =Number(birthSplit[3]) && birth.getDate() == Number(birthSplit[4))) {return false;
    }
    return true;
  }else if(len == 18) {
    regBirth = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/i);
    birthSplit = input.match(regBirth);
    birth = new Date(birthSplit[2] + '/' + birthSplit[3] + '/' + birthSplit[4]);
    if(! (birth.getFullYear() ==Number(birthSplit[2]) && (birth.getMonth() + 1) = =Number(birthSplit[3]) && birth.getDate() == Number(birthSplit[4))) {return false;
    }
    // Verify the verification code
    let valnum;
    let arrInt = new Array(7.9.10.5.8.4.2.1.6.3.7.9.10.5.8.4.2);
    let arrCh = new Array('1'.'0'.'X'.'9'.'8'.'7'.'6'.'5'.'4'.'3'.'2');
    let nTemp = 0, i;
    for (i = 0; i < 17; i++) {
      nTemp += input.substr(i, 1) * arrInt[i];
    }
    valnum = arrCh[nTemp % 11];
    if(valnum ! = input.substr(17.1)) {
      return false;
    }
    return true;
  }
  return false;
}

Copy the code

Mail check

function isEmail(email) {
  return /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(email);
}
Copy the code