JS中常见的编码和解码方式

228 阅读2分钟

URL中的编解码

在RFC对URL进行约定的时候规定,URL只能使用英文字母、阿拉伯数字和某些标点符号,不能使用其他文字和符号

这意味着,如果URL中有汉字,就必须编码后使用,但是RFC并没有规定具体的编码方法,而是交给应用程序(浏览器)自己决定

这就导致了在不同的操作系统、不同的浏览器、不同的网页字符集的情况下,URL将得到完全不同的编码结果

为此JS提供了对URL进行编码的方式,以保证浏览器在得到URL后可以直接使用,而不会有任何的“插手”的机会

encodeURI

encodeURI方法会对整个URL进行编码, encodeURI方法对应的解码函数是decodeURI方法

// 编码
const url = encodeURI('http://www.example.com/this is a 测试')

console.log(url) // => http://www.example.com/this%20is%20a%20%E6%B5%8B%E8%AF%95

// 解码
console.log(decodeURI(url)) // => http://www.example.com/this is a 测试

encodeURI方法主要用于对整个URL进行编码

因此除了常见的符号以外,对其他一些在网址中有特殊含义的符号 encodeURI方法也会对其进行编码,例如/ ? : & # = '

encodeURIComponent

encodeURIComponentencodeURI编码的范围更大

const url = 'https://www.google.com'

console.log(encodeURI(url)) // => https://www.google.com
console.log(encodeURIComponent(url)) // => https%3A%2F%2Fwww.google.com

encodeURIComponent方法主要用于对URL中的参数进行编码

const activityUrl = encodeURIComponent('http://www.example.com/activity/测试')

const url = `http://www.example.com?share-url=${activityUrl}`

console.log(url)
// => http://www.example.com?share-url=http%3A%2F%2Fwww.example.com%2Factivity%2F%E6%B5%8B%E8%AF%95

console.log(decodeURIComponent(url))
// => http://www.example.com?share-url=http://www.example.com/activity/测试
  1. JS最早的编解码方式是escape, 不过该方法在MDN上已经不在推荐使用
  2. 如果需要编码整个URL,那么使用encodeURI方法进行编码
  3. 如果需要对URL中的参数进行编码的时候,推荐使用encodeURIComponent方法

字符串和base64之间的转换

const username = 'Klaus'

// string -> base64
const base64Name = btoa(username)

console.log(base64Name) // => S2xhdXM==

// base64 -> string
console.log(atob(base64Name)) // => Klaus