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

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

获取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>


网络异常,图片无法展示
|


对于一些数据类型的判断


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,
    }


相关文章
|
机器学习/深度学习 人工智能 并行计算
5分钟掌握开源图神经网络框架DGL使用
近几年神经网络在人工智能领域的成功应用,让它备受关注和热捧。但是,它自身依然具有本质上的局限性,以往的神经网络都是限定在欧式空间内,这和大多数实际应用场景并不符合,因此,也阻碍了它在很多领域的实际落地应用。
5分钟掌握开源图神经网络框架DGL使用
|
8月前
|
人工智能 安全 API
OpenClaw不“吃灰”指南:全平台部署+免费API配置+102个即用场景解析+避坑手册
2026年,AI工具的核心价值已从“对话响应”转向“落地执行”。但多数用户仍困在“聊得热闹,做得有限”的困境——AI能写方案、改文字,却无法从头到尾独立完成一件完整任务。而OpenClaw作为首个开源本地部署的AI Agent平台,彻底打破这一局限:它不是单纯的聊天机器人,而是能连接20+平台、自动执行任务的“数字员工”——早上自动整理行业新闻推送到飞书、自动分拣100封客户邮件、监控GitHub代码漏洞并告警,这些场景现在就能落地。
1003 9
|
8月前
|
人工智能 Linux API
9.9元上手OpenClaw超级助理:阿里云一键部署+本地搭建+百炼API配置+避坑指南
2026年,AI已经从“辅助聊天”进化为“真正替人干活”的执行智能体,而OpenClaw(曾用名Clawdbot、Moltbot,俗称龙虾AI)正是这场变革中的标杆产品。它不再是只能给出文字建议的对话工具,而是能直接操控设备、处理文件、收发邮件、编写代码、管理日程、抓取数据的全天候数字员工。为了让普通用户也能零门槛用上这款强大工具,阿里云在2026年3月推出OpenClaw专属一键部署方案,新用户首月仅需9.9元,即可拥有2核2G、40GB ESSD、200Mbps带宽的预装环境,10分钟内完成全流程搭建。
755 7
|
9月前
|
自然语言处理 数据可视化 安全
关于CMS?CMS的核心概念与分类简介
CMS为非技术人员提供内容管理,支持多用户协作、模板统一和本地化适配,涵盖通用、垂直及企业级类型,适应不同场景需求。
929 2
|
9月前
|
文字识别 Linux 数据安全/隐私保护
Python实战:用代码轻松搞定PDF页面方向调整
本文详解Python自动化修复PDF页面方向问题:针对扫描件倒置、混合横纵页等痛点,对比Spire.PDF(精准控制)与PyPDF2(轻量快捷)两大方案,提供单页/批量/智能旋转、加密PDF处理及元数据保留等实用技巧,助你高效完成PDF方向矫正。(239字)
661 2
|
11月前
|
JSON fastjson Java
Spring Boot 默认对Json的处理
本文详解Spring Boot中JSON处理,涵盖Jackson与FastJson的使用对比、null值处理及统一返回结构封装,提升接口数据规范性与可读性。
|
9月前
|
人工智能
从"任天堂仿作"到动态封禁:生成式游戏的内容审核难题
The Verge测评揭示Project Genie在模仿经典游戏风格时的版权困境:关键词过滤易被绕过,输出审核难定“相似度”,人工审核不可持续。问题核心在于AI能否合法模仿创作风格——法律尚未明确,技术尚不成熟。平台需透明规则、分层发布与版权方协作。
432 0
|
11月前
|
消息中间件 运维 物联网
语音通知
适用于科技公司服务器及物联网设备异常告警场景,通过语音电话实时通知处理人。需开通语音服务,申请资质、话术与模板,支持变量替换,可选公共或专属号码模式。通过API调用实现自动化呼叫,并支持CallId追踪与消息回执推送,便于集成至运维系统。
|
数据可视化 开发者 智能硬件
鸿蒙5开发宝藏案例分享---一多断点开发实践
本文深入解析鸿蒙开发中的六大核心案例,涵盖动态网格布局、自适应导航栏、阅读器分栏模式、视频播放器多形态适配、数据看板动态布局及表单自动优化。通过具体应用场景与代码实现,解决多端适配痛点,如手机单列到平板多列的智能计算、折叠屏半开状态特殊布局等。同时提供开发者避坑指南与终极适配方案架构,帮助开发者灵活应对复杂需求,提升开发效率。
|
数据库 数据安全/隐私保护 UED
如何开发CRM系统中的订单管理板块(附架构图+流程图+代码参考)
CRM系统中的订单管理板块是企业数字化转型的关键工具,能够高效管理客户订单、提升销售效率和客户满意度。本文详解订单管理的功能设计、业务流程、开发技巧及代码实现,助力企业优化订单流程、提高业绩。