// 假设有一个JavaScript变量包含特殊字符
let username = "张三's account";
let password = "pa$$w0rd with space";
// 使用encodeURIComponent对每个参数进行编码
let encodedUsername = encodeURIComponent(username);
let encodedPassword = encodeURIComponent(password);
// 构造URL字符串
let url = `https://example.com/login?username=${encodedUsername}&password=${encodedPassword}`;
console.log(url); // 输出类似:https://example.com/login?username=%E5%BC%A0%E4%B8%89%27s%20account&password=pa%24%24w0rd%20with%20space
// 在服务器端解码参数
// 以Node.js为例:
let { query: { username, password } } = url.parse(request.url, true);
username = decodeURIComponent(username);
password = decodeURIComponent(password);
// 现在username和password已经恢复成原始字符串