- 使用encodeURIComponent()和decodeURIComponent()函数:
// 编码
var encodedUrl = encodeURIComponent("https://www.example.com?name=张三&age=20");
console.log(encodedUrl); // https%3A%2F%2Fwww.example.com%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D20
// 解码
var decodedUrl = decodeURIComponent(encodedUrl);
console.log(decodedUrl); // https://www.example.com?name=张三&age=20
- 使用encodeURI()和decodeURI()函数:
// 编码
var encodedUrl = encodeURI("https://www.example.com?name=张三&age=20");
console.log(encodedUrl); // https://www.example.com?name=%E5%BC%A0%E4%B8%89&age=20
// 解码
var decodedUrl = decodeURI(encodedUrl);
console.log(decodedUrl); // https://www.example.com?name=张三&age=20
- 使用escape()和unescape()函数(不推荐使用,已被废弃):
// 编码
var encodedUrl = escape("https://www.example.com?name=张三&age=20");
console.log(encodedUrl); // https%3A%2F%2Fwww.example.com%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D20
// 解码
var decodedUrl = unescape(encodedUrl);
console.log(decodedUrl); // https://www.example.com?name=张三&age=20