工具函数(不知道你们能不能用得上)

1,945 阅读2分钟

获取URL中指定的查询参数值

在理解这个函数之前,我们需要介绍一些几个api

  • encodeURIComponent 这个api对于大多数字符都是转义的,对于下面这部分不会转义。
不转义的字符:
    A-Z a-z 0-9 - _ . ! ~ * ' ( )
  • encodeURI 他会转义所有字符,将其转为%编码的格式。但是下面这类字符不会被转义。这个也就是通常我们复制url到文本编辑器时所转义的格式了。 类型 | 包含 | | ------ | ----------------------------------------- | | 保留字符 | ; , / ? : @ & = + $ | | 非转义的字符 | 字母 数字 - _ . ! ~ * ' ( ) | | 数字符号 | #
  • decodeURIComponent 这个api的解码能力更加强大,因为他可以解码encodeURI, encodeURIComponent编码的url。
  • decodeURI 这个api的只能解码由encodeURI编码的url了。

下面给出一个实例,可以自己举例子测试一下。

    const url = "http://localhost:8080?name=张----_昊&age=30"
    const encode = encodeURIComponent(url) 
    console.log("编码 encodeURIComponent", encode) // http%3A%2F%2Flocalhost%3A8080%3Fname%3D%E5%BC%A0----_%E6%98%8A%26age%3D30
    const encode2 = encodeURI(url)
    console.log("编码 encodeURI", encode2) // http://localhost:8080?name=%E5%BC%A0----_%E6%98%8A&age=30
    const decode = decodeURIComponent(encode)
    console.log("解码", decode) // http://localhost:8080?name=张----_昊&age=30
    const decode2 = decodeURI(encode)
    console.log("解码", decode2) // http%3A%2F%2Flocalhost%3A8080%3Fname%3D张----_昊%26age%3D30

工具函数

    const getURLParam = function (name, targetUrl) {
      var reg = new RegExp('[?&]' + name + '=([^&]+)')
      targetUrl = targetUrl || window.location.search
      var newurl = decodeURIComponent(targetUrl)
      return newurl.match(reg) ? RegExp.$1 : null
    }

    const url = "http://localhost:8080?name=张昊&age=30"
    console.log(getURLParam("name", url)) // 张昊

按照json对象中的key升序排列

    jsonSortId = function (json) {
      let arr = []
      for (var key in json) {
        arr.push(key)
      }
      // 默认是升序排列,将key升序,然后在取值,返回。
      arr.sort()
      let newjson = {}
      for (var i in arr) {
        var key = arr[i]
        newjson[key] = json[key]
      }
      return newjson
    }

将json对象转为url参数

    parseParams = (data) => {
      try {
        var tempArr = []
        for (var i in data) {
          // 将一些非ascii或者uri的保留字转为%编码
          var key = encodeURIComponent(i)
          var value = encodeURIComponent(data[i])
          tempArr.push(key + '=' + value)
        }
        // 在进行拼接
        var urlParamsStr = tempArr.join('&')
        return urlParamsStr
      } catch (err) {
        return ''
      }
    }

剪切板

    const clipboard = (text) => {
      return new Promise((resolve, reject) => {
        // 创建隐藏的 Textarea 标签,并将文本放入其中
        let textarea = document.createElement('textarea')

        textarea.style.position = 'absolute'
        textarea.style.top = '0'
        textarea.style.left = '0'
        textarea.style.border = 'none'
        textarea.style.margin = '0'
        textarea.style.padding = '0'
        textarea.style.opacity = '0'
        textarea.value = text

        document.body.appendChild(textarea)

        // 复制 Textarea 标签的文本
        textarea.select()
        document.execCommand('copy')

        // 移除 Textarea 标签
        document.body.removeChild(textarea)

        resolve()
      })
    }

测试这个工具函数

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <p id="p">这里是需要复制的文本</p>
      <div id="div">点击复制</div>
      <script>
        var clipboard = (text) => {
          return new Promise((resolve, reject) => {
            // 创建隐藏的 Textarea 标签,并将文本放入其中
            let textarea = document.createElement('textarea')

            textarea.style.position = 'absolute'
            textarea.style.top = '0'
            textarea.style.left = '0'
            textarea.style.border = 'none'
            textarea.style.margin = '0'
            textarea.style.padding = '0'
            textarea.style.opacity = '0'
            textarea.value = text

            document.body.appendChild(textarea)

            // 复制 Textarea 标签的文本
            textarea.select()
            document.execCommand('copy')

            // 移除 Textarea 标签
            document.body.removeChild(textarea)

            resolve()
          })
        }
        const p = document.getElementById("p")
        const div = document.getElementById("div")
        div.onclick = function() {
          clipboard(p.innerText).then(() => {
            console.log("复制成功")
          }).catch(err => {
            console.log("复制失败")
          })
        }
      </script>
    </body>
    </html>

剪切板测试.gif

对于一些数据类型的判断

    const funProto = Function.prototype
    const objProto = Object.prototype

    const getPrototypeOf = Object.getPrototypeOf

    const objToString = objProto.toString
    const hasOwnProperty = objProto.hasOwnProperty
    const funToString = funProto.toString

    // 检查给定的值是否是 dom 元素
    export function isElement(value) {
      return !!(value && value.nodeType === 1)
    }

    // 检查给定的值是否是 null
    export function isNull(value) {
      return value === null
    }

    // 检查给定的值是否是 undefined
    export function isUndefined(value) {
      return value === void 0
    }

    // 检查给定的值是否是 NaN
    // 这和原生的 isNaN 函数不一样,如果变量是 undefined,原生的 isNaN 函数也会返回 true
    export function isNaN(value) {
      return window.isNaN(value) && value !== value
    }

    // 检查给定的值是否是数值
    export function isNumber(value) {
      return objToString.call(value) === '[object Number]' && !isNaN(value)
    }

    // 检查给定的值是否是字符串
    export function isString(value) {
      return objToString.call(value) === '[object String]'
    }

    // 检查给定的值是否是布尔值
    export function isBoolean(value) {
      return (
        value === true ||
        value === false ||
        objToString.call(value) === '[object Boolean]'
      )
    }

    // 检查给定的值是否是正则表达式
    export function isRegExp(value) {
      return objToString.call(value) === '[object RegExp]'
    }

    // 检查给定的值是否是日期对象
    export function isDate(value) {
      return objToString.call(value) === '[object Date]'
    }

    // 检查给定的值是否是函数
    export function isFunction(value) {
      return (
        objToString.call(value) === '[object Function]' ||
        typeof value === 'function'
      )
    }

    // 检查给定的值是否是数组
    export function isArray(value) {
      return objToString.call(value) === '[object Array]'
    }

    // 检查给定的值是否是对象
    export function isObject(value) {
      return !!value && typeof value === 'object'
    }

    // 检查给定的值是否是纯对象,纯对象是指通过 {} 或 new Object() 声明的对象
    export function isPlainObject(value) {
      if (!value || objToString.call(value) !== '[object Object]') {
        return false
      }

      var prototype = getPrototypeOf(value)

      if (prototype === null) {
        return true
      }

      var constructor =
        hasOwnProperty.call(prototype, 'constructor') && prototype.constructor

      return (
        typeof constructor === 'function' &&
        funToString.call(constructor) === funToString.call(Object)
      )
    }

    //
    export default {
      element: isElement,
      null: isNull,
      undefined: isUndefined,
      nan: isNaN,
      number: isNumber,
      string: isString,
      boolean: isBoolean,
      regexp: isRegExp,
      date: isDate,
      function: isFunction,
      array: isArray,
      object: isObject,
      plainObject: isPlainObject,
    }