Skip to content
On this page

项目中常用的工具函数总结

应持续总结

  1. 获取变量的类型

    js
    function getVarType(data,isLower){
        const type = Object.prototype.toString.call(data).split(' ')[1].replace(']', '')
        return isLower ? type.toLowerCase() : type
    }
    
    test:
    console.log(getVarType([1, 23]), true)   => array 
    
  2. 类数组转数组

    js
    const sArr = { 0: 1, 1: 3, length: 2 }
    
    1. [].slice.call(sArr, [index])  index 代表从哪一位开始截取
    2. Array.form(sArr)
    
  3. 正则校验

    js
    const regStr = {
      email: /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
      ip: /^((?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?:(\/([0-9]+)))?)$/,
      telephone: /^((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/,
      mobile: /^1[3|4|5|7|8|9][0-9]{9}$/,
      userName: /^[a-zA-Z\d@_]+$/,
      number: /^\d+$/,
      password: /^(?=.*\d)(?=.*[A-Za-z])(?=.*[@#\$%\&*_\-]).{8,32}$/,
    }
    
    
    /**
     * 校验字符串是够满足邮箱格式
     * @param type 选择正则的类型 email ip telephone mobile
     * @param str 传入的字符串
     */
    
    export function regValidate (type, str) {
      if (typeof str !== 'string' || !regStr[type]) return false
      const checkStr = new RegExp(regStr[type])
      return checkStr.test(str)
    }
    
  4. textarea中的换行符是/r/n 或者 /r, 但我们渲染内容到html时,并不能起到换行的作用,有两个处理方法

    js
    1. js将/r/n, /n 替换为 <br />
      /**
         * 替换 文本框中换行符 为 br标签
         * @param str
         * @returns {string|*}
         */
        export function replaceLineFeed(str) {
          if (typeof str === 'string') {
            return str.replace(/\n/g, '<br>').replace(/ /g, '&nbsp;')
          }
          return str
        }  
    
    2. css属性 设置该显示区域支持换行符换行
    	{  white-space: pre-wrap }
    https://developer.mozilla.org/zh-CN/docs/Web/CSS/white-space
    
  5. 复制内容到剪切板上

    js
    /**
     * 复制内容到剪切板
     * */
    export function handleCopy (data) {
      try {
        const oInput = document.createElement('input')
        oInput.value = data
        document.body.appendChild(oInput)
        oInput.select()
        document.execCommand('Copy')
        oInput.remove()
        return true
      }catch (e) {
        return false
      }
    }
    
  6. 导出文件,待完善不同的文件类型

    js
    /**
     * 导出文件
     * @param data 二进制流
     * @param fileName 文件名
     * @param type 文件类型
     */
    export function exportFile(data, fileName, type ) {
      if (data) {
        const typeMap = {
          excel: 'application/vnd.ms-excel'
        }
        const blob = new window.Blob([data], {
          type: typeMap[type]
        })
        const downUrl = window.URL.createObjectURL(blob)
    
        const a = window.document.createElement('a')
        a.href = downUrl
        a.download = fileName
        a.click()
        setTimeout(() => {
          window.URL.revokeObjectURL(downUrl)
        }, 1000)
      }
    }
    
  7. 根据文件的buffers, 判断是不是真实的图片类型

    场景: 一般是根据后缀名去判断这个文件的类型,但这样的话,如果后缀名和文件类型并不符合的话,是无法判断是否是真的符合文件类型要求的。根据Magic Number去判断。

    js

文件类型对应的Magic Number 参考网站: https://www.garykessler.net/library/file_sigs.html

/** * 根据传入的buffers 判断是否是图片类型 * @param buffers * @returns {string} */ export function isImage (buffers) { const check = (headers) => { return (buffers, options = { offset: 0 }) => headers.every( (header, index) => header === buffers[options.offset + index] ) } const imageMagicNumber = { png: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], icon: [0x00,0x00,0x01,0x00], _icon: [0x69,0x63,0x6E,0x73], bmp: [0x42, 0x4D], jpg: [0xff, 0xd8, 0xff], jpeg: [0xff, 0xd8, 0xff], gif: [0x47, 0x49, 0x46, 0x38], } const data = Object.entries(imageMagicNumber).find(([key, values]) => check(values)(buffers)) return data ? data[0] : '' }