字符串encodeURIComponent/decodeURIComponent编码方法

    URL编码方法是属于 Global 全局对象的,encodeURI()encodeURIComponent() 方法可以对URI(通用资源标示符)进行编码,以便发送给浏览器,有效的URI中不能包含某些字符,例如空格。而这两个URI编码方法就可以对URI进行编码,它们用特殊的UTF-8编码替换所有无效的字符,从而让浏览器能够接受和理解。

    其中 encodeURI() 主要用于整个URI,而 encodeURICompoent() 主要用于对URI中的某一段进行编码。它们的主要区别在于,encodeURI() 不会对本身属于URI的特殊字符进行编码,例如冒号、正斜杠、问号和井字号;而 encodeURIComponent 则会对它发现的任何非标准字符进行编码

    与上述两个方法相对应的两个方法分别是 decodeURI()decodeURIComponent() 。其中,decodeURI() 只能对使用 encodeURI() 替换的字符进行解码。decodeURIComponent() 能够解码使用 encodeURIComponent() 编码的所有字符串。

简单例举编码方法的使用案例

// 修改密码保存方法
submitPwd() {
      const userId = this.userIdnew
      this.$refs['changeForm'].validate((valid) => {
        if (valid) {
          if (this.changeForm.password === this.changeForm.enterpassword) { // 判断两次设置密码是否一致
            this.changeForm.password = encodeURIComponent(utils.encrypt(this.changeForm.password)) // 对密码进行编码
            changePassword(userId, this.changeForm.password).then((response) => { // 将新密码传递给后台,修改密码
              if (response && response.code === 0) {
                this.dialogChangePwd = false
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '修改失败'
                })
              }
            })
          } else {
            alert('密码必须一致')
          }
        }
      })
    }
// 格式化时间
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1) // lastIndexOf() 从右向左查找某个字符在字符串中最后一次出现的位置
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值