A js tools

Remove the blank space

const trim = function(str, type) { // Remove whitespace, type: 1- all whitespace 2- front and back whitespace 3- front whitespace 4- back whitespace
  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
  }
}

Copy the code

Check whether it is empty

// Check whether it is null
function isEmpty (obj) {
  if (obj == null || obj === void 0 || obj.toString() === ' ') {
    return true
  }
  return false
}
Copy the code

Check if it is an array

const isArray = function(arr) { // Check if it is an array
  return Object.prototype.toString.call(arr) === '[object Array]'
}
Copy the code

Determines whether two arrays are equal

const arrayEqual = function(arr1, arr2) { // Check whether two arrays are equal
  if (arr1 === arr2) return true;
  if(arr1.length ! = arr2.length)return false;
  for (let i = 0; i < arr1.length; ++i) {
    if(arr1[i] ! == arr2[i])return false;
  }
  return true;
}
Copy the code

Time and timestamp conversion

const stamp = { // Time, timestamp conversion
  getTime: function(time) { // Time to 10 bit timestamp
    let date = time ? new Date(time) : new Date(a)return Math.round(date.getTime() / 1000)},timeToStr: function(time, fmt) { // 10 bit timestamp transfer time
    return new Date(time * 1000).pattern(fmt || 'yyyy-MM-dd')}}Copy the code

Time formatting

const formatDate = function(fmt, date) { [' yyyY-MM-DD hh: MM :ss', time]
  if (typeofdate ! = ='object') { date = ! date ?new Date() : new Date(date)
  }
var o = {
    'M+': date.getMonth() + 1./ / in
    'd+': date.getDate(), / /,
    'h+': date.getHours(), / / hour
    'm+': date.getMinutes(), / / points
    's+': date.getSeconds(), / / SEC.
    'q+': Math.floor((date.getMonth() + 3) / 3), / / quarter
    'S': date.getMilliseconds() / / ms
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + ' ').substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp('(' + k + ') ').test(fmt)) {
      fmt = fmt.replace(RegExp. $1,RegExp.$1.length === 1)? (o[k]) : (('00' + o[k]).substr((' ' + o[k]).length)))
    }
  }
  return fmt
}
Copy the code

Common regular validation

const checkStr = function(str, type) { // Regex is used for validation
  switch (type) {
    case 'phone': // Mobile phone number
      return / ^ 1 [3 4 5 6 7 | | | | | | 8, 9] [0-9] {9} $/.test(str)
    case 'tel': / / machine
      return / ^ (0 \ d {2, 3} - \ d {7, 8}) (\ d {1, 4})? $/.test(str)
    case 'card': / / id card
      return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str)
    case 'pwd': // The password must start with a letter and contain 6 to 18 letters, digits, and underscores (_)
      return / ^ \ [a zA - Z] $/ w {5} in 2.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': / / email
      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 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': / / digital
      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': / / the capital
      return /^[A-Z]+$/.test(str)
    case 'HTML': / / HTML tags
      return / < (" [^ "] * '|' [^ '] * '| [^' "> >]) * /.test(str)
    default:
      return true}}Copy the code

String case conversion

const changeCase = function(str, type) { // String uppercase conversion Type: 1: uppercase first letter 2: home letter mother lowercase letter 3: uppercase conversion 4: all uppercase 5: all lowercase letter
  type = type || 4
  switch (type) {
    case 1:
      return str.replace(/\b\w+\b/g.function(word) {
        return word.substring(0.1).toUpperCase() + word.substring(1).toLowerCase()
      })
    case 2:
      return str.replace(/\b\w+\b/g.function(word) {
        return word.substring(0.1).toLowerCase() + word.substring(1).toUpperCase()
      })
    case 3:
      return str.split(' ').map(function(word) {
        if (/[a-z]/.test(word)) {
          return word.toUpperCase()
        } else {
          return word.toLowerCase()
        }
      }).join(' ')
    case 4:
      return str.toUpperCase()
    case 5:
      return str.toLowerCase()
    default:
      return str
  }
}
Copy the code

Convert Arabic numerals to Uppercase Chinese numerals

const numberToChinese = function(num) { // Translate Arabic numerals into Chinese uppercase digits
  let AA = new Array('zero'.'一'.'二'.'三'.'four'.'five'.'六'.'seven'.'eight'.'九'.'ten')
  let BB = new Array(' '.'ten'.'best'.'仟'.'萬'.'億'.'point'.' ')
  let a = (' ' + num).replace(/(^0*)/g.' ').split('. ')
  let k = 0
  let re = ' '
  for (let i = a[0].length - 1; i >= 0; i--) {
    switch (k) {
      case 0:
        re = BB[7] + re
        break
      case 4:
        if (!new RegExp('0{4}//d{' + (a[0].length - i - 1) + '} $').test(a[0])) {
          re = BB[4] + re
        }
        break
      case 8:
        re = BB[5] + re
        BB[7] = BB[5]
        k = 0
        break
    }
    if (k % 4= = =2 && a[0].charAt(i + 2)! = =0 && a[0].charAt(i + 1) = = =0) {
      re = AA[0] + re
    }
    if (a[0].charAt(i) ! = =0) {
      re = AA[a[0].charAt(i)] + BB[k % 4] + re
    }
    k++
  }
  if (a.length > 1) { // Add the decimal part (if any)
    re += BB[6]
    for (let i = 0; i < a[1].length; i++) {
      re += AA[a[1].charAt(i)]
    }
  }
  if (re === 'ten') {
    re = 'ten'
  }
  if (re.match(A / / ^) && re.length === 3) {
    re = re.replace('一'.' ')}return re
}
Copy the code

Gets the string argument in the link

function getQueryString (name) {
  let reg = new RegExp('(^ | &)' + name + '= (/ ^ & *) (& | $)'.'i')
  let r = window.location.search.substr(1).match(reg)
  let context = ' '
  if(r ! =null) {
    context = r[2]
  }
  reg = null
  r = null
  return context == null || context == ' ' || context == 'undefined' ? ' ' : context
}
Copy the code

Url parameter to object

const parseQueryString = function(url) { // The url argument goes to the objecturl = ! url ?window.location.href : url;
  if (url.indexOf('? ') = = = -1) {
    return {};
  }
  let search = url[0= = ='? ' ? url.substr(1) : url.substring(url.lastIndexOf('? ') + 1);
  if (search === ' ') {
    return {};
  }
  search = search.split('&');
  let query = {};
  for (let i = 0; i < search.length; i++) {
    let pair = search[i].split('=');
    query[decodeURIComponent(pair[0=]]decodeURIComponent(pair[1] | |' ');
  }
  return query;
}
Copy the code

Object serialization

const stringfyQueryString = function(obj) { // Object serialization
  if(! obj)return ' ';
  let pairs = [];
  for (let key in obj) {
    let value = obj[key];
    if (value instanceof Array) {
      for (let i = 0; i < value.length; ++i) {
        pairs.push(encodeURIComponent(key + '[' + i + '] ') + '=' + encodeURIComponent(value[i]));
      }
      continue;
    }
    pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
  }
  return pairs.join('&');
}
Copy the code

Function image stabilization

const debounce = function(func, wait, Immediate) {func function, number of milliseconds to wait for execution,immediate true,false,immediate Then the effect of the function can continue without raising the event for n seconds. return function() { let context = this; let args = arguments; if (timeout) clearTimeout(timeout); if (immediate) { var callNow = ! timeout; timeout = setTimeout(() => { timeout = null; }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(function() { func.apply(context, args) }, wait); }}}Copy the code

Function of the throttle

Javascript const random = function(min, If (arguments.length === 2) {return math.floor (min + math.random () * ((Max + 1) -min))} else {return math.floor (min + math.random () * (Max + 1) -min))} else { return null } }Copy the code

Browser storage

Localhost Local storage

const store = { // Local storage
  set: function(name, value, day) { / / set
    let d = new Date(a)let time = 0
    day = (typeof(day) === 'undefined'| |! day) ?1 : day // Time, the default storage is 1 day
    time = d.setHours(d.getHours() + (24 * day)) / / ms
    localStorage.setItem(name, JSON.stringify({
      data: value,
      time: time
    }))
  },
  get: function(name) { / / to get
    let data = localStorage.getItem(name)
    if(! data) {return null
    }
    let obj = JSON.parse(data)
    if (new Date().getTime() > obj.time) { / / overdue
      localStorage.removeItem(name)
      return null
    } else {
      return obj.data
    }
  },
  clear: function(name) { / / to empty
    if (name) { // Delete the cache with key name
      localStorage.removeItem(name)
    } else { // Clear all
      localStorage.clear()
    }
  }
}
Copy the code

Cookie operation

const cookie = { [set, get, del]
  set: function(name, value, day) {
    let oDate = new Date()
    oDate.setDate(oDate.getDate() + (day || 30))
    document.cookie = name + '=' + value + '; expires=' + oDate + "; path=/;"
  },
  get: function(name) {
    let str = document.cookie
    let arr = str.split('; ')
    for (let i = 0; i < arr.length; i++) {
      let newArr = arr[i].split('=')
      if (newArr[0] === name) {
        return newArr[1]}}},del: function(name) {
    this.set(name, ' ', -1)}}Copy the code

Request class encapsulation

Native Ajax operations

const ajax = function(conf) { / / ajax operations
  let url = conf.url,
    data = conf.data,
    senData = [], // Encapsulate data
    async= conf.async ! = =undefined ? conf.async : true.// true is an asynchronous request
      type = conf.type || 'get'.// The default request is get
      dataType = conf.dataType || 'json',
      contenType = conf.contenType || 'application/x-www-form-urlencoded',
      success = conf.success,
      error = conf.error,
      isForm = conf.isForm || false./ / whether the formdata
      header = conf.header || {}, // Header information
      xhr = ' ' // Create an Ajax engine object
  if (data == null) {
    senData = ' '
  } else if (typeof data === 'object' && !isForm) { // If data is an object, convert it to a string
    for (var k in data) {
      senData.push(encodeURIComponent(k) + '=' + encodeURIComponent(data[k]))
    }
    senData = senData.join('&')}else {
    senData = data
  }
  try {
    xhr = new ActiveXObject('microsoft.xmlhttp') // IE kernel series browser
  } catch (e1) {
    try {
      xhr = new XMLHttpRequest() // Non-IE kernel browser
    } catch (e2) {
      if(error ! =null) {
        error('Ajax requests not supported')}}}; xhr.open(type, type ! = ='get' ? url : url + '? ' + senData, async)
  if(type ! = ='get' && !isForm) {
    xhr.setRequestHeader('content-type', contenType)
  }
  for (var h inheader) { xhr.setRequestHeader(h, header[h]) } xhr.send(type ! = ='get' ? senData : null)
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        if (dataType === 'json'&& success ! =null) {
          let res = ' '
          try {
            res = eval('(' + xhr.responseText + ') ')}catch (e) {
            console.log(e)
          }
          success(res) // Convert json strings to JS objects
        };
      } else {
        if(error ! =null) {
          error('Communication failed! ' + xhr.status)
        }
      }
    }
  }
}
Copy the code

Fetch encapsulates the request

const fetch = function(url, setting) { // Fetch encapsulates the request
  let opts = { // Set the initial value of the parameter
    method: (setting.method || 'GET').toUpperCase(), // Request mode
    headers: setting.headers || {}, // Request header Settings
    credentials: setting.credentials || true.// Sets whether cookies are sent together
    body: setting.body || {},
    mode: setting.mode || 'no-cors'.// You can set cors, no-cors, same-origin
    redirect: setting.redirect || 'follow'.// follow, error, manual
    cache: setting.cache || 'default' // Set cache mode (default, reload, no-cache)
  }
  let dataType = setting.dataType || 'json' // Parsing mode
  let data = setting.data || ' ' / / parameters
  let paramsFormat = function(obj) { // Parameter format
    var str = ' '
    for (var i in obj) {
      str += `${i}=${obj[i]}& `
    }
    return str.split(' ').slice(0, -1).join(' ')}if (opts.method === 'GET') {
    url = url + (data ? `?${paramsFormat(data)}` : ' ')}else {
    setting.body = data || {}
  }
  return new Promise((resolve, reject) = > {
    fetch(url, opts).then(async res => {
      let data = dataType === 'text' ? await res.text() : dataType === 'blob' ? await res.blob() : await res.json()
      resolve(data)
    }).catch(e= > {
      reject(e)
    })
  })
}

Copy the code

Dom manipulation

Asynchronous loading js | | CSS | | style

const loadRes = function(name, type, fn) { / / load js | | CSS | | style
  let ref
  if (type === 'js') { / / external js
    ref = document.createElement('script')
    ref.setAttribute('type'.'text/JavaScript')
    ref.setAttribute('src', name)
  } else if (type === 'css') { / / external CSS
    ref = document.createElement('link')
    ref.setAttribute('rel'.'stylesheet')
    ref.setAttribute('type'.'text/css')
    ref.setAttribute('href', name)
  } else if (type === 'style') { // style
    ref = document.createElement('style')
    ref.innerhtml = name
  }
Copy the code

Js to get the element style

const getRealStyle = function(obj, styleName) { // get the element style.
var realStyle = null
  if (obj.currentStyle) {
    realStyle = obj.currentStyle[styleName]
  } else if (window.getComputedStyle) {
    realStyle = window.getComputedStyle(obj, null)[styleName]
  }
  return realStyle
}
Copy the code

Dom instantiation operations

const dom = {
  $: function(selector) {
    let type = selector.substring(0.1)
    if (type === The '#') {
      if (document.querySelecotor) return document.querySelector(selector)
      return document.getElementById(selector.substring(1))}else if (type === '. ') {
      if (document.querySelecotorAll) return document.querySelectorAll(selector)
      return document.getElementsByClassName(selector.substring(1))}else {
      return document['querySelectorAll' ? 'querySelectorAll' : 'getElementsByTagName'](selector)
    }
  },
  hasClass: function(ele, name) { /* Test class name */
    return ele.className.match(new RegExp('(\\s|^)' + name + '(\\s|$)'))},addClass: function(ele, name) { /* Add the class name */
    if (!this.hasClass(ele, name)) ele.className += ' ' + name
  },
  removeClass: function(ele, name) { /* Delete the class name */
    if (this.hasClass(ele, name)) {
      let reg = new RegExp('(\\s|^)' + name + '(\\s|$)')
      ele.className = ele.className.replace(reg, ' ')}},replaceClass: function(ele, newName, oldName) { /* Replace the class name */
    this.removeClass(ele, oldName)
    this.addClass(ele, newName)
  },
  siblings: function(ele) { /* Get sibling node */
    console.log(ele.parentNode)
    let chid = ele.parentNode.children,
      eleMatch = []
    for (let i = 0, len = chid.length; i < len; i++) {
      if(chid[i] ! == ele) { eleMatch.push(chid[i]) } }return eleMatch
  },
  getByStyle: function(obj, name) { /* Gets the inter-line style attribute */
    if (obj.currentStyle) {
      return obj.currentStyle[name]
    } else {
      return getComputedStyle(obj, false)[name]
    }
  },
  domToStirng: function(htmlDOM) { /* DOM to string */
    var div = document.createElement('div')
    div.appendChild(htmlDOM)
    return div.innerHTML
  },
  stringToDom: function(htmlString) { /* String to DOM */
    var div = document.createElement('div')
    div.innerHTML = htmlString
    return div.children[0]}}Copy the code

Check that the image is loaded successfully

const imgLoadAll = function(arr, callback) { // Image loading
  let arrImg = []
  for (let i = 0; i < arr.length; i++) {
    let img = new Image()
    img.src = arr[i]
    img.onload = function() {
      arrImg.push(this)
      if (arrImg.length == arr.length) {
        callback && callback()
      }
    }
  }
}
Copy the code

The image address goes to base64

const getBase64 = function(img) { GetBase64 (url). Then (function(base64){},function(err){});
  let getBase64Image = function(img, width, height) { // Call width, height, pass the specific pixel value, control the size, do not pass the default image size
    let canvas = document.createElement("canvas");
    canvas.width = width ? width : img.width;
    canvas.height = height ? height : img.height;
    let ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0.0, canvas.width, canvas.height);
    let dataURL = canvas.toDataURL();
    return dataURL;
  }
  let image = new Image();
  image.crossOrigin = ' ';
  image.src = img;
  let deferred = $.Deferred();
  if (img) {
    image.onload = function() {
      deferred.resolve(getBase64Image(image));
    }
    returndeferred.promise(); }}Copy the code

Base64 image download function

const downloadFile = function(base64, fileName) { // Base64 image download function
  let base64ToBlob = function(code) {
    let parts = code.split('; base64,');
    let contentType = parts[0].split(':') [1];
    let raw = window.atob(parts[1]);
    let rawLength = raw.length;
    let uInt8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {
      type: contentType
    });
  };
  let aLink = document.createElement('a');
  let blob = base64ToBlob(base64); //new Blob([content]);
  let evt = document.createEvent("HTMLEvents");
  evt.initEvent("click".true.true); //initEvent without the following two parameters will report an error event type under FF, whether it bubbles, and whether it prevents the default behavior of the browser
  aLink.download = fileName;
  aLink.href = URL.createObjectURL(blob);
  aLink.click();
}
Copy the code

Whether the browser supports webP images

const isSupportWebP = function() { // Check whether the browser supports webP images
  return!!!!! [].map &&document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') = =0;
}
Copy the code

Different position character characters

const insertAtCursor = function(dom, val) { // Insert character at cursor position
  if (document.selection) {
    dom.focus()
    let sel = document.selection.createRange()
    sel.text = val
    sel.select()
  } else if (dom.selectionStart || dom.selectionStart == '0') {
    let startPos = dom.selectionStart
    let endPos = dom.selectionEnd
    let restoreTop = dom.scrollTop
    dom.value = dom.value.substring(0, startPos) + val + dom.value.substring(endPos, dom.value.length)
    if (restoreTop > 0) {
      dom.scrollTop = restoreTop
    }
    dom.focus()
    dom.selectionStart = startPos + val.length
    dom.selectionEnd = startPos + val.length
  } else {
    dom.value += val
    dom.focus()
  }
}
Copy the code

H5 soft keyboard retracts and unwinds the keyboard

const h5Resize = function(downCb, upCb) { // Listen for the change in the value of window.innerHeight when the software keyboard is up [downCb when the soft keyboard is up, the retractable callback,upCb when the soft keyboard is up]
  var clientHeight = window.innerHeight;
  downCb = typeof downCb === 'function' ? downCb : function() {}
  upCb = typeof upCb === 'function' ? upCb : function() {}
  window.addEventListener('resize'.() = > {
    var height = window.innerHeight;
    if (height === clientHeight) {
      downCb();
    }
    if(height < clientHeight) { upCb(); }}); }Copy the code

Environmental judgment

Device Check: Android, ios, and Web

const isDevice = function() { // Determine whether it is Android, ios or Web
  var ua = navigator.userAgent.toLowerCase()
  if (ua.match(/iPhone\sOS/i) = = ='iphone os' || ua.match(/iPad/i) = = ='ipad') { // ios
    return 'iOS'
  }
  if (ua.match(/Android/i) = = ='android') {
    return 'Android'
  }
  return 'Web'
}
Copy the code

Check whether the terminal is a PC

const isPC = function() { // Whether it is a PC
  let userAgentInfo = navigator.userAgent
  let Agents = ['Android'.'iPhone'.'SymbianOS'.'Windows Phone'.'iPad'.'iPod']
  let flag = true
  for (let v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false
      break}}return flag
}
Copy the code

Determine whether it is wechat

Const isWx = function () {/ / determine whether for WeChat var ua = window. The navigator. UserAgent. ToLowerCase () if (ua) match (/ MicroMessenger/I) === 'micromessenger') { return true } return false }Copy the code

Browser environment tools

Text copy function

const copyTxt = function(text, fn) { // Copy function
  if (typeof document.execCommand ! = ='function') {
    console.log('Copy failed, please long press copy')
    return
  }
  var dom = document.createElement('textarea')
  dom.value = text
  dom.setAttribute('style'.'display: block; width: 1px; height: 1px; ')
  document.body.appendChild(dom)
  dom.select()
  var result = document.execCommand('copy')
  document.body.removeChild(dom)
  if (result) {
    console.log('Copy successful')
    typeof fn === 'function' && fn()
    return
  }
  if (typeof document.createRange ! = ='function') {
    console.log('Copy failed, please long press copy')
    return
  }
  var range = document.createRange()
  var div = document.createElement('div')
  div.innerhtml = text
  div.setAttribute('style'.'height: 1px; fontSize: 1px; overflow: hidden; ')
  document.body.appendChild(div)
  range.selectNode(div)
  var selection = window.getSelection()
  console.log(selection)
  if (selection.rangeCount > 0) {
    selection.removeAllRanges()
  }
  selection.addRange(range)
  document.execCommand('copy')
  typeof fn === 'function' && fn()
  console.log('Copy successful')}Copy the code