This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.


It’s Friday again, come and fish! Today, let’s take a look at some useful JavaScript tools and functions to help you improve your development efficiency! It is not easy to organize, if you think it is useful, please click a “like”!

1. Digital operations

(1) Generate random numbers in a specified range

export const randomNum = (min, max) = > Math.floor(Math.random() * (max - min + 1)) + min;
Copy the code

(2) digit separation in thousandths

export const format = (n) = > {
    let num = n.toString();
    let decimals = ' ';
    // Is there a decimal number
    num.indexOf('. ') > -1 ? decimals = num.split('. ') [1] : decimals;
    let len = num.length;
    if (len <= 3) {
        return num;
    } else {
        let temp = ' ';
        let remainder = len % 3;
        decimals ? temp = '. ' + decimals : temp;
        if (remainder > 0) { // Not an integer multiple of 3
            return num.slice(0, remainder) + ', ' + num.slice(remainder, len).match(/\d{3}/g).join(', ') + temp;
        } else { // an integer multiple of 3
            return num.slice(0, len).match(/\d{3}/g).join(', ') + temp; }}}Copy the code

2. Array operations

(1) The array is out of order

export const arrScrambling = (arr) = > {
    for (let i = 0; i < arr.length; i++) {
      const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i;
      [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
    }
    return arr;
}
Copy the code

(2) Array flattening

export const flatten = (arr) = > {
  let result = [];

  for(let i = 0; i < arr.length; i++) {
    if(Array.isArray(arr[i])) {
      result = result.concat(flatten(arr[i]));
    } else{ result.push(arr[i]); }}return result;
}
Copy the code

(3) get random number in the array

export const sample = arr= > arr[Math.floor(Math.random() * arr.length)];
 
Copy the code

3. String operations

(1) Generate random strings

export const randomString = (len) = > {
    let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
    let strLen = chars.length;
    let randomStr = ' ';
    for (let i = 0; i < len; i++) {
        randomStr += chars.charAt(Math.floor(Math.random() * strLen));
    }
    return randomStr;
};
Copy the code

(2) Uppercase the first letter of the string

export const fistLetterUpper = (str) = > {
    return str.charAt(0).toUpperCase() + str.slice(1);
};
Copy the code

(3) The middle four digits of the phone number change to *

export const telFormat = (tel) = > {
  	tel = String(tel); 
    return tel.substr(0.3) + "* * * *" + tel.substr(7);
};
Copy the code

(4) Camel naming is converted to short horizontal naming

export const getKebabCase = (str) = > {
    return str.replace(/[A-Z]/g.(item) = > The '-' + item.toLowerCase())
}
Copy the code

(5) the short line naming is converted into camel naming

export const getCamelCase = (str) = > {
    return str.replace( /-([a-z])/g.(i, item) = > item.toUpperCase())
}
Copy the code

(6) Full Angle is converted into half Angle

export const toCDB = (str) = > {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    code = str.charCodeAt(i);
    if (code >= 65281 && code <= 65374) {
      result += String.fromCharCode(str.charCodeAt(i) - 65248);
    } else if (code == 12288) {
      result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
    } else{ result += str.charAt(i); }}return result;
}

Copy the code

(7) Half Angle is converted into full Angle

export const toDBC = (str) = > {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    code = str.charCodeAt(i);
    if (code >= 33 && code <= 126) {
      result += String.fromCharCode(str.charCodeAt(i) + 65248);
    } else if (code == 32) {
      result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32);
    } else{ result += str.charAt(i); }}return result;
}

Copy the code

4. Format conversion

(1) Numbers are converted to uppercase amounts

export const digitUppercase = (n) = > {
    const fraction = ['Angle'.'points'];
    const digit = [
        'zero'.'one'.'. '.'叁'.'boss'.'wu'.'land'.'pure'.'捌'.'nine'
    ];
    const unit = [
        ['元'.'万'.'亿'],
        [' '.'pick up'.'or'.'仟']]. n =Math.abs(n);
    let s = ' ';
    for (let i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(Zero /. /.' ');
    }
    s = s || 'the whole';
    n = Math.floor(n);
    for (let i = 0; i < unit[0].length && n > 0; i++) {
        let p = ' ';
        for (let j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/ (zero). * $/ zero.' ').replace($/ / ^.'zero') + unit[0][i] + s;
    }
    return s.replace(/ (zero). * zero yuan /.'元')
        .replace(/ (zero). +/g.'zero')
        .replace(Whole $/ / ^.'zero integer');
};
Copy the code

(2) Numbers are converted into Chinese numbers

export const intToChinese = (value) = > {
 const str = String(value);
 const len = str.length-1;
 const idxs = [' '.'ten'.'best'.'千'.'万'.'ten'.'best'.'千'.'亿'.'ten'.'best'.'千'.'万'.'ten'.'best'.'千'.'亿'];
 const num = ['zero'.'一'.'二'.'三'.'four'.'five'.'六'.'seven'.'eight'.'九'];
 return str.replace(/([1-9]|0+)/g.( $, $1, idx, full) = > {
    let pos = 0;
    if($1[0]! = ='0'){
      pos = len-idx;
      if(idx == 0 && $1[0] = =1 && idxs[len-idx] == 'ten') {return idxs[len-idx];
      }
     	return num[$1[0]] + idxs[len-idx];
    } else {
     	let left = len - idx;
     	let right = len - idx + $1.length;
     	if(Math.floor(right / 4) - Math.floor(left / 4) > 0){
      		pos = left - left % 4;
     	}
     	if( pos ){
      		return idxs[pos] + num[$1[0]];
     	} else if( idx + $1.length >= len ){
      		return ' ';
     	}else {
      		return num[$1[0]]}}}); }Copy the code

5. Perform storage operations

(1) Store loalStorage

export const loalStorageSet = (key, value) = > {
    if(! key)return;
    if (typeofvalue ! = ='string') {
        value = JSON.stringify(value);
    }
    window.localStorage.setItem(key, value);
};
Copy the code

(2) Obtain localStorage

export const loalStorageGet = (key) = > {
    if(! key)return;
    return window.localStorage.getItem(key);
};
Copy the code

(3) Delete localStorage

export const loalStorageRemove = (key) = > {
    if(! key)return;
    window.localStorage.removeItem(key);
};
Copy the code

(4) storage sessionStorage

export const sessionStorageSet = (key, value) = > {
  	if(! key)return;
    if (typeofvalue ! = ='string') {
    		value = JSON.stringify(value);
    }
    window.sessionStorage.setItem(key, value)
};
Copy the code

(5) Obtain the sessionStorage

export const sessionStorageGet = (key) = > {
  	if(! key)return;
    return window.sessionStorage.getItem(key)
};
Copy the code

(6) Delete sessionStorage

export const sessionStorageRemove = (key) = > {
  	if(! key)return;
    window.sessionStorage.removeItem(key)
};
Copy the code

6. Operation cookies

(1) Set cookies

export const setCookie = (key, value, expire) = > {
    const d = new Date(a); d.setDate(d.getDate() + expire);document.cookie = `${key}=${value}; expires=${d.toUTCString()}`
};

Copy the code

(2) Read cookies

export const getCookie = (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

(3) Delete cookies

export const delCookie = (key) = > {
    document.cookie = `The ${encodeURIComponent(key)}=; expires=The ${new Date()}`
};
Copy the code

7. Format verification

(1) Verify the ID card number

export const checkCardNo = (value) = > {
    let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return reg.test(value);
};
Copy the code

(2) Check whether Chinese is included

export const haveCNChars => (value) = > {
    return /[\u4e00-\u9fa5]/.test(value);
}
Copy the code

(3) Verify whether it is the postal code of Mainland China

export const isPostCode = (value) = > {
    return / ^ (1-9] [0-9] {5} $/.test(value.toString());
}
Copy the code

(4) Check whether the IP address is IPv6

export const isIPv6 = (str) = > {
    return Boolean(str.match(/:/g)? str.match(/:/g).length<=7:false && / : : /.test(str)?/ ^ ([\ da - f] {1, 4} (: | : :)) {1, 6} [\ da - f] {1, 4} $/ I.test(str):/ ^ ([\ da - f] {1, 4} :) {7} [\ da - f] {1, 4} $/ I.test(str));
}
Copy the code

(5) Verify whether the email address is used

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

(6) Verify whether it is a mobile phone number in Mainland China

export const isTel = (value) = > {
    return / ^ 1,4,5,6,7,8,9 [3] [0-9] {9} $/.test(value.toString());
}
Copy the code

(7) Check whether emoji is included

export const isEmojiCharacter = (value) = > {
  	value = String(value);
    for (let i = 0; i < value.length; i++) {
        const hs = value.charCodeAt(i);
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (value.length > 1) {
                const ls = value.charCodeAt(i + 1);
                const uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f) {
                    return true; }}}else if (value.length > 1) {
            const ls = value.charCodeAt(i + 1);
            if (ls == 0x20e3) {
                return true; }}else {
            if (0x2100 <= hs && hs <= 0x27ff) {
                return true;
            } else if (0x2B05 <= hs && hs <= 0x2b07) {
                return true;
            } else if (0x2934 <= hs && hs <= 0x2935) {
                return true;
            } else if (0x3297 <= hs && hs <= 0x3299) {
                return true;
            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030
                    || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b
                    || hs == 0x2b50) {
                return true; }}}return false;
}
Copy the code

8. Operating URL

(1) Obtain the URL parameter list

export const GetRequest = () = > {
    let url = location.search;
    const paramsStr = /. + \? (. +) $/.exec(url)[1]; / / will be? I'm going to pull out the string
    const paramsArr = paramsStr.split('&'); // Split the string with & and store it in the array
    let paramsObj = {};
    // Save params to the object
    paramsArr.forEach(param= > {
      if (/ = /.test(param)) { // Handle arguments with value
        let [key, val] = param.split('='); // Split key and value
        val = decodeURIComponent(val); / / decoding
        val = /^\d+$/.test(val) ? parseFloat(val) : val; // Determine whether to convert to a number
        if (paramsObj.hasOwnProperty(key)) { // Add a value if the object has a key
          paramsObj[key] = [].concat(paramsObj[key], val);
        } else { // If the object does not have this key, create the key and set the valueparamsObj[key] = val; }}else { // Handle arguments without value
        paramsObj[param] = true; }})return paramsObj;
};
Copy the code

(2) Check whether the URL is valid

export const getUrlState = (URL) = > {
  let xmlhttp = new ActiveXObject("microsoft.xmlhttp");
  xmlhttp.Open("GET", URL, false);
  try {
    xmlhttp.Send();
  } catch (e) {
  } finally {
    let result = xmlhttp.responseText;
    if (result) {
      if (xmlhttp.Status == 200) {
        return true;
      } else {
        return false; }}else {
      return false; }}}Copy the code

(3) Splicing key-value pairs into URL parameters

export const params2Url = (obj) = > {
     let params = []
     for (let key in obj) {
       params.push(`${key}=${obj[key]}`);
     }
     return encodeURIComponent(params.join('&'))}Copy the code

(4) Modify parameters in the URL

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

(5) Delete the specified parameters in the URL

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

9. Equipment judgment

(1) Judge whether it is mobile or PC device

export const isMobile = () = > {
  if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
		return 'mobile';
  }
  return 'desktop';
}
Copy the code

(2) Determine whether it is an Apple or an Android mobile device

export const isAppleMobileDevice = () = > {
  let reg = /iphone|ipod|ipad|Macintosh/i;
  return reg.test(navigator.userAgent.toLowerCase());
}
Copy the code

(3) Determine whether it is an Android mobile device

export const isAndroidMobileDevice = () = > {
  return /android/i.test(navigator.userAgent.toLowerCase());
}
Copy the code

(4) Determine whether the operating system is Windows or Mac

export const osType = () = > {
    const agent = navigator.userAgent.toLowerCase();
    const isMac = /macintosh|mac os x/i.test(navigator.userAgent);
  	const isWindows = agent.indexOf("win64") > =0 || agent.indexOf("wow64") > =0 || agent.indexOf("win32") > =0 || agent.indexOf("wow32") > =0;
    if (isWindows) {
        return "windows";
    }
    if(isMac){
        return "mac"; }}Copy the code

(5) Determine whether it is wechat /QQ built-in browser

export const broswer = () = > {
    const ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) = ="micromessenger") {
        return "weixin";
    } else if (ua.match(/QQ/i) = ="qq") {
        return "QQ";
    }
    return false;
}
Copy the code

(6) Browser model and version

export const getExplorerInfo = () = > {
    let t = navigator.userAgent.toLowerCase();
    return 0 <= t.indexOf("msie")? {//ie < 11
        type: "IE".version: Number(t.match(/msie ([\d]+)/) [1])} :!!!!! t.match(/trident\/.+? rv:(([\d.]+))/)? {// ie 11
        type: "IE".version: 11
    } : 0 <= t.indexOf("edge")? {type: "Edge".version: Number(t.match(/edge\/([\d]+)/) [1])} :0 <= t.indexOf("firefox")? {type: "Firefox".version: Number(t.match(/firefox\/([\d]+)/) [1])} :0 <= t.indexOf("chrome")? {type: "Chrome".version: Number(t.match(/chrome\/([\d]+)/) [1])} :0 <= t.indexOf("opera")? {type: "Opera".version: Number(t.match(/opera.([\d]+)/) [1])} :0 <= t.indexOf("Safari")? {type: "Safari".version: Number(t.match(/version\/([\d]+)/) [1])}, {type: t,
        version: -1}}Copy the code

10. Browser operations

1) Scroll to the top of the page

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

Scroll to the bottom of the page

export const scrollToBottom = () = > {
  window.scrollTo(0.document.documentElement.clientHeight);  
}
Copy the code

(3) Scroll to the specified element area

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

(4) Obtain the height of the visible window

export const 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

(5) Obtain the visual window width

export const getPageViewWidth = () = > {
    return (document.compatMode == "BackCompat" ? document.body : document.documentElement).clientWidth;
}
Copy the code

(6) Open the browser in full screen

export const toFullScreen = () = > {
    let element = document.body;
    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

(7) Exit the full-screen browser

export const 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

11. Time operation

(1) Current time

export const nowTime = () = > {
    const now = new Date(a);const year = now.getFullYear();
    const month = now.getMonth();
    const date = now.getDate() >= 10 ? now.getDate() : ('0' + now.getDate());
    const hour = now.getHours() >= 10 ? now.getHours() : ('0' + now.getHours());
    const miu = now.getMinutes() >= 10 ? now.getMinutes() : ('0' + now.getMinutes());
    const sec = now.getSeconds() >= 10 ? now.getSeconds() : ('0' + now.getSeconds());
    return +year + "Year" + (month + 1) + "Month" + date + "Day" + hour + ":" + miu + ":" + sec;
}
Copy the code

(2) Formatting time

export const dateFormater = (formater, time) = > {
    let date = time ? new Date(time) : new Date(),
        Y = date.getFullYear() + ' ',
        M = date.getMonth() + 1,
        D = date.getDate(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
    return formater.replace(/YYYY|yyyy/g, Y)
        .replace(/YY|yy/g, Y.substr(2.2))
        .replace(/MM/g,(M<10 ? '0' : ' ') + M)
        .replace(/DD/g,(D<10 ? '0' : ' ') + D)
        .replace(/HH|hh/g,(H<10 ? '0' : ' ') + H)
        .replace(/mm/g,(m<10 ? '0' : ' ') + m)
        .replace(/ss/g,(s<10 ? '0' : ' ') + s)
}
// dateFormater('YYYY-MM-DD HH:mm:ss')
// dateFormater('YYYYMMDDHHmmss')
Copy the code

12. JavaScript operations

(1) Prevent bubbling events

export const stopPropagation = (e) = > { 
    e = e || window.event; 
    if(e.stopPropagation) {    // W3C prevents bubbling methods
        e.stopPropagation(); 
    } else { 
        e.cancelBubble = true; // IE prevents bubbling}}Copy the code

(2) Anti-shake function

export const debounce = (fn, wait) = > {
  let timer = null;

  return function() {
    let context = this,
        args = arguments;

    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    timer = setTimeout(() = > {
      fn.apply(context, args);
    }, wait);
  };
}
Copy the code

(3) Throttling function

export const throttle = (fn, delay) = > {
  let curTime = Date.now();

  return function() {
    let context = this,
        args = arguments,
        nowTime = Date.now();

    if (nowTime - curTime >= delay) {
      curTime = Date.now();
      returnfn.apply(context, args); }}; }Copy the code

(4) Data type judgment

export const getType = (value) = > {
  if (value === null) {
    return value + "";
  }
  // Determine if the data is a reference type
  if (typeof value === "object") {
    let valueClass = Object.prototype.toString.call(value),
      type = valueClass.split("") [1].split("");
    type.pop();
    return type.join("").toLowerCase();
  } else {
    // Determine whether the data is a basic data type or a function
    return typeofvalue; }}Copy the code

(5) Object deep copy

export const deepClone = (obj, hash = new WeakMap() = > {// The date object returns a new date object
  if (obj instanceof Date) {return new Date(obj);
  } 
  The regular object returns a new regular object directly
  if (obj instanceof RegExp) {return new RegExp(obj);     
  }
  // If the reference is cyclic, use weakMap to solve the problem
  if (hash.has(obj)){
  	return hash.get(obj);
  }
  // Get a description of all of the object's own attributes
  let allDesc = Object.getOwnPropertyDescriptors(obj);
  // Walks through the properties of all keys of the passed argument
  let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc)
  
  hash.set(obj, cloneObj)
  for (let key of Reflect.ownKeys(obj)) { 
    if(typeof obj[key] === 'object'&& obj[key] ! = =null){
    	cloneObj[key] = deepClone(obj[key], hash);
    } else{ cloneObj[key] = obj[key]; }}return cloneObj
}
Copy the code