前端JavaScript数据处理常用工具

将base64的图片url数据转换为Blob
function base64Url2Blob(dataUrl, type, name) {
   // 将base64的图片url数据转换为Blob
   const binaryString = window.atob(dataUrl.split(',')[1])
   const arrayBuffer = new ArrayBuffer(binaryString.length)
   const intArray = new Uint8Array(arrayBuffer)
   for (let i = 0, j = binaryString.length; i < j; i++) {
     intArray[i] = binaryString.charCodeAt(i)
   }
   const data = [intArray]; let blob
   try {
     blob = new Blob(data, { type: type })
     blob.name = name
   } catch (e) {
     window.BlobBuilder = window.BlobBuilder ||
         window.WebKitBlobBuilder ||
         window.MozBlobBuilder ||
         window.MSBlobBuilder
     if (e.name === 'TypeError' && window.BlobBuilder) {
       const builder = new window.BlobBuilder()
       builder.append(arrayBuffer)
       blob = builder.getBlob(type)
     } else {
       // do something
     }
   }
   return blob
}
生成guid
// 生成guid
function S4() {
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
function guid() {
      return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
},
获取带参数地址中的参数对象
 function urlParams(search) {
   if (!search) return ''
    const searchArr = search.split('&')
    const searchObj = {}
    searchArr.forEach(val => {
      const itemArr = val.split('=')
      searchObj[itemArr[0]] = itemArr[1]
    })

    return searchObj
 }
判断字符串是否是JSON字符串
function isJson(str) {
  if (typeof (str) === 'string') {
    try {
      var obj = JSON.parse(str)
      if (typeof (obj) === 'object' && obj) {
        return true
      } else {
        return false
      }
    } catch (e) {
      return false
    }
  }
},
复制到粘贴板
function copyToClip(content, message, vm) {
  var aux = document.createElement('input')
  aux.setAttribute('value', JSON.stringify(content))
  document.body.appendChild(aux)
  aux.select()
  document.execCommand('copy')
  document.body.removeChild(aux)
  if (message == null) {
    //do something
  } else {
   //do something
  }
}
当前之间XXX之前/之后(举一反三)
function beforeHours(hours) {
  // 当前时间hours小时之前
  return new Date(new Date().setHours((new Date().getHours() - hours)))
}

function afterHours(hours) {
  // 当前时间hours小时之后
  return new Date(new Date().setHours((new Date().getHours() + hours)))
}

function beforeMonth(month) {
  // 当前时间month个月之前
  return new Date((new Date()).setMonth((new Date()).getMonth() - month))
}

function afterMonth(month) {
  // 当前时间month个月之后
  return new Date((new Date()).setMonth((new Date()).getMonth() + month))
}
日期格式化处理
// 日期格式化处理
const padLeftZero = function(str) {
  return ('00' + str).substr(str.length)
}
const formatDate = function(date, fmt) {
  if (!date) return ''
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'S': date.getMilliseconds() // 毫秒
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

export default formatDate
日期反转

将yyyy-MM-DD hh:mm:ss格式转换成yyyy,mm,dd,hh,mm,ss

// 将yyyy-MM-DD hh:mm:ss格式转换成yyyy,mm,dd,hh,mm,ss
const unformatDate = function(str) {
  if (typeof (str) === 'string') {
    const a = str.split(' ') // 年月日和时分秒分开
    const [yyyy, MM, dd] = a[0].split('-')
    const [hh, mm, ss] = a[1].split(':')
    return {
      y: yyyy,
      M: Number(MM) - 1,
      d: dd,
      h: hh,
      m: mm,
      s: ss
    }
  }
}
去除所有空格
const removeSpace = function(str) {
  // 去除空格
  if (!str) {
    return ''
  } else {
    return str.replace(/(\s*)|(\s*$)/g, '')
  }
}
去除首尾空格
const removeSpaceSE = function(str) {
  // 去除首尾空格
  if (!str) {
    return ''
  } else {
    return str.replace(/(^\s*)|(\s*$)/g, '')
  }
}
cookie增删改
// 获取cookie
const getCookie = function(cname) {
  const name = cname + '='
  const ca = document.cookie.split(';')
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i]
    while (c.charAt(0) === ' ') c = c.substring(1)
    if (c.indexOf(name) !== -1) {
      return  c.split('=')[1]
    }
  }
  return ''
}
// 设置cookie
const setCookie = function(cname, cvalue, exdays) {
  const d = new Date()
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000))
  const expires = 'expires=' + d.toUTCString()
  document.cookie = cname + '=' + cvalue + '; ' + expires
}
// 清除cookie
const clearCookie = function(key) {
  setCookie(key, '', -1)
}
去除文本中的表情包
// 去掉文本中的表情包
const removeBlank = function(str) {
  // 去空格
  str = str.trim()
  var ret = ''
  for (var i = 0; i < str.length; i++) {
    if (str[i] !== ' ') {
      ret += str[i]
    }
  }
  return ret
}
const filterNicknameWithEmoji = function(nickname) {
  // const regStr = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[A9|AE]\\u3030|\uA9|\uAE|\u3030/ig
  // 更新的原因是发现字符串F9ua96y000被过滤成F96y000
  const regStr = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|\u3030/ig
  let nickname_filter = ''
  if (regStr.test(nickname)) {
    nickname_filter = nickname.replace(regStr, '')
    nickname_filter = removeBlank(nickname_filter)
    return nickname_filter
  }

  return nickname
}
格式化字符串中的内容(举一反三)
const getFormatCode = function(strValue) {
  /*
  * 根据Value格式化为带有换行、空格格式的HTML代码
  * @param strValue {String} 需要转换的值
  * @return  {String}转换后的HTML代码
  * @example
  * getFormatCode("测\r\n\s试")  =>  “测<br/> 试”
  */
  return strValue.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ')
}
const setFormatCode = function(strValue) {
  const reg = new RegExp('<br/>', 'g')
  return strValue.replace(reg, '\n')
}
判断是否包含html
const isContainHtml = function(str) {
  const reg = new RegExp(/<[^<>]+>/g)

  return reg.test(str)
}
判断是否是正整数
// 是否是正整数判断
const isPositiveInteger = function(num) {
  const re = /^[0-9]+$/
  return re.test(num)
}
队列的封装
function Queue() {
  var items = []
  // enqueue 从队列尾部添加一个元素
  this.enqueue = function(item) {
    items.push(item)
  }
  // dequeue 从队列头部删除一个元素
  this.dequeue = function() {
    return items.shift()
  }
  // head 返回头部的元素
  this.head = function() {
    return items[0]
  }
  // size 返回队列大小
  this.size = function() {
    return items.length
  }
  // clear清空队列
  this.clear = function() {
    items = []
  }
  // isEmpty判断队列是否为空
  this.isEmpty = function() {
    return items.length === 0
  }
}
栈的封装
function Stack() {
  var items = [] // 使用数组存储数据

  // push方法向栈里压入一个元素
  this.push = function(item) {
    items.push(item)
  }

  // pop方法把栈顶的元素弹出
  this.pop = function(item) {
    return items.pop()
  }

  // top方法返回栈顶元素
  this.top = function() {
    return items[items.length - 1]
  }

  // isEmpty返回栈是否为空
  this.isEmpty = function() {
    return items.length === 0
  }

  // size方法返回栈的大小
  this.size = function() {
    return items.length
  }

  // clear 清空栈
  this.clear = function() {
    items = []
  }
}
统一处理利率 为4位;大于4位保留到最后一位非零
// 统一处理利率 为4位;大于4位保留到最后一位非零
const rateProcess = function(rate) {
  if (!rate) {
    return
  }
  // 特殊情况,返回的rate使用科学计数法
  if (String(rate).indexOf('-') > -1) {
    return rate
  }
  // 判小数点后的位数
  // 大于四位就从后往前除0,遇到非0就停止处理
  const rateList = String(rate).split('.')
  // rateList[0] 小数点前的数字,rateList[1]小数点后的数字
  if (rateList[1].length === 4) {
    // 等于四位不变
    return String(rate)
  } else if (rateList[1].length < 4) {
    // 小于四位就补齐0
    return Number(rate).toFixed(4)
  } else {
    // 大于四位就从后往前删0,遇到非0就停止处理,并返回
    const array = rateList[1].split('') // 转成数组
    while (array[array.length - 1] === '0' && array.length > 4) {
      array.pop()
    }

    return rateList[0] + '.' + array.join('')
  }
}
按照一定间隔分割数组
// 按照一定间隔分割数组
const chunkArray = function(arr, num) {
  num = num * 1 || 1
  const ret = []
  arr.forEach((element, i) => {
    if (i % num === 0) {
      ret.push([])
    }
    ret[ret.length - 1].push(element)
  })
  return ret
}
定时器管理方案
window.queryMessageTimer // 声明定时查询消息定时器
window.processTimer // 声明处理中数量定时器
window.queryBulletinTimer // 声明查询滚动公告定时器

// 兼容性处理
let state; let visibilityChange
if (typeof document.hidden !== 'undefined') {
  visibilityChange = 'visibilitychange'
  state = 'visibilityState'
} else if (typeof document.mozHidden !== 'undefined') {
  visibilityChange = 'mozvisibilitychange'
  state = 'mozVisibilityState'
} else if (typeof document.msHidden !== 'undefined') {
  visibilityChange = 'msvisibilitychange'
  state = 'msVisibilityState'
} else if (typeof document.webkitHidden !== 'undefined') {
  visibilityChange = 'webkitvisibilitychange'
  state = 'webkitVisibilityState'
}
function timerManager(store, router) {
  var handler = function() {
    if (document[state] === 'visible') {
      // 页面可见时,触发定时器

      // 触发消息定时器
      if (!window.queryMessageTimer) {
        store.dispatch('messageNumber/queryMessageResult', router)
      }

      // 触发处理中数量定时器
      if (!window.processTimer) {
        store.dispatch('processNumber/queryProcessingCount')
      }

      // 触发公告栏定时器
      if (!window.queryBulletinTimer) {
        store.dispatch('queryBulletin/queryBulletinResult')
      }
    }
    if (document[state] === 'hidden') {
      // 页面不可见时,清除定时器

      // 清除消息定时器
      if (window.queryMessageTimer) {
        clearInterval(window.queryMessageTimer) // 清除定时器
        window.queryMessageTimer = null // 引用置空
      }

      // 清除处理中数量定时器
      if (window.processTimer) {
        window.clearInterval(window.processTimer) // 清除定时器
        window.processTimer = null // 引用置空
      }

      // 清除公告栏定时器
      if (window.queryBulletinTimer) {
        window.clearInterval(window.queryBulletinTimer) // 清除定时器
        window.queryBulletinTimer = null // 引用置空
      }
    }
  }
  // 添加监听器,清除或者触发定时器
  document.addEventListener(visibilityChange, handler, false)
}
是否是中国身份证号
 function isChineseID(number) {
    number = String(number).toLowerCase()
    function isDateLegal(y, m, d) {
      const st = [m, d, y.length < 4 ? '19' + y : y].join('/').replace(/\b0/g, '')

      const dt = new Date(Date.parse(st))
      return [dt.getMonth() + 1, dt.getDate(), dt.getFullYear()].join('/') === st
    }
    function checkDate(y, m, d) {
      const st = [m, d, y.length < 4 ? '19' + y : y].join('/').replace(/\b0/g, '')
      const dt = new Date(Date.parse(st))
      return [dt.getMonth() + 1, dt.getDate(), dt.getFullYear()].join('/') === st
    }
    if (/^\d{15}$/.test(number)) {
      return checkDate.apply(null, number.match(/^.{6}(..)(..)(..)/).slice(1))
    }
    if (/^\d{17}[\dx]$/i.test(number)) {
      let sum = 0; const times = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      for (let i = 0; i < 17; i++) { sum += parseInt(number.charAt(i), 10) * times[i] }
      if ('10x98765432'.charAt(sum % 11) !== number.charAt(17)) { return false }
      return isDateLegal.apply(null, number.match(/^.{6}(.{4})(..)(..)/).slice(1))
    }
    return false
  },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值