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
}