Development often use some JS methods

1.JS Checks whether it is empty

/** * JS to check whether it is null *@param val
 * @returns {boolean}* /
function isNull(val) {
    if (val == undefined || val == null || val == "" || val == ' '
        || val == "undefined" || val == "null" || val == "NULL") {
        return true;
    }
    return false;
}
Copy the code

2.JS timestamp is converted to time

timeStamp2String(1526552438244); 	/ / the 2018-05-17 18:20:38
Copy the code
/** * JS timestamp is converted to time *@param time
 * @returns* /
function timeStamp2String(time){
    var datetime = new Date(a); datetime.setTime(time);var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    var hour = datetime.getHours()< 10 ? "0" + datetime.getHours() : datetime.getHours();
    var minute = datetime.getMinutes()< 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
    var second = datetime.getSeconds()< 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
    return year + "-" + month + "-" + date+""+hour+":"+minute+":"+second;
}
Copy the code

3.JS timestamp to time (general version, you can customize the format)

Formats include:

  1. Y-M-D
  2. Y-M-D h:m:s
  3. Y year M month D day
  4. Y year M month D day h hour M minute
  5. Y year M month D day h hour M minute s second

Example: console.log(formatDate(1500305226034, ‘Y year M month D day h: M :s’)) ==> 23:27:06, 17 July 2017

/** * JS timestamp is converted to time *@param time
 * @returns* /
function formatDate(timestamp, formats){
    formats = formats || 'Y-M-D';
	var myDate = undefined;
	if (timestamp) {
            if (typeof(timestamp) ! ='string') {
		myDate = timestamp;
            } 
            else {
                myDate = new Date(timestamp); }}else {
            myDate = new Date(a); }var year = myDate.getFullYear();
	var month = formatDigit(myDate.getMonth() + 1);
	var day = formatDigit(myDate.getDate());
	var hour = formatDigit(myDate.getHours());
	var minute = formatDigit(myDate.getMinutes());
	var second = formatDigit(myDate.getSeconds());
	return formats.replace(/Y|M|D|h|m|s/g.(matches) = > {
		return {
			Y: year,
			M: month,
			D: day,
			h: hour,
			m: minute,
			s: second
		} [matches];
	});
}
Copy the code

4.JS generates a random integer with specified bits

getRandomNum(6); / / 292868

/** * JS generates a random integer * with the specified number of digits@param count
 * @returns {string}* /
function getRandomNum(count){
    var arr = new Array;
    var reNum = "";
    for(var i=0; i<count; i++){ arr[i] =parseInt(Math.random()*10);
        reNum += String(arr[i]);
    }
    return reNum;
}
Copy the code

5. Remove whitespace

Type: 1- All Spaces 2- Front space 3- Front space 4- Back space strTrim(‘ 125FFF 111 ‘, 1)// 125FFF111

/** * JS generates a random integer * with the specified number of digits@param str
 * @param Type 1- All Spaces 2- Front space 3- Front space 4- Back space *@returns {string}* /
function strTrim(str, type) {
    type = type || 2
    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

6.JS formats the remaining time from ${endTime}

formatRemainTime(“2021-8-21 00:00:00”); // 9 days 12 hours 2 minutes 8 seconds

/** * JS format now ${endTime} remaining time *@param  {Date} endTime
 * @return {String}* /
function formatRemainTime(endTime) {
    var startDate = new Date(a);// Start time
    var endDate = new Date(endTime); // End time
    var t = endDate.getTime() - startDate.getTime(); / / time
    var d = 0,
        h = 0,
        m = 0,
        s = 0;
    if (t >= 0) {
        d = Math.floor(t / 1000 / 3600 / 24);
        h = Math.floor(t / 1000 / 60 / 60 % 24);
        m = Math.floor(t / 1000 / 60 % 60);
        s = Math.floor(t / 1000 % 60);
    }
    return d + "Day" + h + "Hour" + m + "Minutes" + s + "Seconds";
}
Copy the code

7.JS format ${startTime} past the current time

formatPassTime(“2018-5-17 10:19:00”); // 1 hour ago

/** * JS format ${startTime} elapsed time *@param  {Date} startTime
 * @return {String}* /
function formatPassTime(startTime) {
    var currentTime = Date.parse(new Date()),
        time = currentTime - new Date(startTime),
        day = parseInt(time / (1000 * 60 * 60 * 24)),
        hour = parseInt(time / (1000 * 60 * 60)),
        min = parseInt(time / (1000 * 60)),
        month = parseInt(day / 30),
        year = parseInt(month / 12);
    if (year) return year + "Years ago";
    if (month) return month + "A month ago.";
    if (day) return day + "Days ago";
    if (hour) return hour + "Hours ago";
    if (min) return min + "Minutes ago.";
    else return 'just';
}
Copy the code

8.JS Base64 string encoding and decoding

base64Encode("test");    // dGVzdA==
base64Decode(test);     // test
Copy the code
/** * BASE64 encryption *@param str
 * @returns {string}* /
function base64Encode(str) {
    return btoa(unescape(encodeURIComponent(str)));
}

/** * BASE64 decryption *@param str
 * @returns {string}* /
function base64Decode(str) {
    return decodeURIComponent(escape(atob(str)));
}
Copy the code

9.JS Checks whether the entered characters have special characters

checkQuote("dasd1! /, /. "); // true checkQuote("52014sdsda"); // falseCopy the code
/** * JS checks if the input character has a special character *@param STR string *@returns True or false; True indicates that special characters are used to verify */ when registering information
function checkQuote(str) {
    var items = new Array("~"."`"."!"."@"."#"."$"."%"."^"."&"."*"."{"."}"."["."]"."(".")");
    items.push(":".";"."'"."|"."\","<",">","?","/","<<",">>","||","/ / ");
    items.push("select"."delete"."update"."insert"."create"."drop"."alter"."trancate");
    str = str.toLowerCase();
    for ( var i = 0; i < items.length; i++) {
        if (str.indexOf(items[i]) >= 0) {
            return true; }}return false;
}
Copy the code

10. Format the mobile phone number with an asterisk (*) in the middle

phoneToStar("16666666666"); * * * * 6666 / / 166Copy the code
/** * JS format the phone number with * instead of * in the middle part@param phone
 * @returns {string | * | void}* /
function phoneToStar( phone ) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/."$1 * * * * $2");
}
Copy the code

11.JS Gets the value of the address bar parameter

// If the current URL is a.html? t1=1&t2=2&t3=3
console.log(getUrlParam("t1"));	/ / 1
Copy the code
/** * JS gets the value of the address bar argument *@param Name Indicates the parameter *@returns {*} If yes, the parameter value is returned; if no, null */ is returned
function getUrlParam(name){
    var reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)");
    var r = window.location.search.substr(1).match(reg);
    if(r ! =null) {
        return unescape(r[2]);
    } else {
        return null; }}Copy the code

JS time personalized output function

// Time display that can be used for list display
console.log(timeFormat(new Date()));	// Example: Just now
Copy the code
/** * JS time personalized output function * 1, < 60s, display as "just" * 2, >= 1min && < 60min, display with the current time difference "XX minutes ago" * 3, >= 60min && < 1day, * 4, >= 1day && < 1year, displays the date "XX month XX day XX:XX" * 5, >= 1year, displays the specific date "XXXX month XX day XX:XX" *@param time
 * @returns {string}* /
function timeFormat(time){
    var date = new Date(time),
        curDate = new Date(),
        year = date.getFullYear(),
        month = date.getMonth() + 10,
        day = date.getDate(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        curYear = curDate.getFullYear(),
        curHour = curDate.getHours(),
        timeStr;

    if(year < curYear){
        timeStr = year +'years'+ month +'month'+ day +'day'+ hour +':'+ minute;
    }else{
        var pastTime = curDate - date,
            pastH = pastTime/3600000;

        if(pastH > curHour){
            timeStr = month +'month'+ day +'day'+ hour +':'+ minute;
        }else if(pastH >= 1){
            timeStr = 'today' + hour +':'+ minute +'points';
        }else{
            var pastM = curDate.getMinutes() - minute;
            if(pastM > 1){
                timeStr = pastM +'Minutes ago';
            }else{
                timeStr = 'just'; }}}return timeStr;
}
Copy the code

13. JS UUID generated

generateUUID();	For example, 7ceb31a7-41b9-45ED-915B-14C7AD0fDDf6
Copy the code
/** * generateUUID Generates UUID *@returns {string} Returns the string */
function generateUUID(){
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g.function(c) {
        var r = (d + Math.random()*16) %16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uuid;
}
Copy the code

14. Function shake

/ / call
let n = 1;
function func () {
    n += 1;
    console.log('n', n);
}
window.onresize = debance(func, 1000);
Copy the code
function debance(fn, delay) {
    let t = null;
    return function() {
        let that = this;
        let args = arguments;
        clearTimeout(t);
        t = setTimeout(function() { fn.apply(context, args); }, delay); }}Copy the code

15. Function throttling

/ / call
let n = 1;
function func () {
    n += 1;
    console.log('n', n);
}
window.onresize = throttle(func, 1000);
Copy the code
function throttle (fn, delay) {
    let preTime = Date.now();
    return function() {
        let that = this;
        let args = arguments;
        let nowTime = Date.now();
        if(preTime + delay < nowTime) { fn.apply(that, args); preTime = nowTime; }}}Copy the code