// 使用 JavaScript 对 URL 进行编码和解码的示例
// 原始字符串
let originalString = "https://example.com/path?name=John Doe&city=New York";
// 使用 encodeURIComponent 对 URL 中的参数进行编码
let encodedUrl = "https://example.com/path?" +
"name=" + encodeURIComponent("John Doe") +
"&city=" + encodeURIComponent("New York");
console.log("原始 URL: " + originalString);
console.log("编码后的 URL: " + encodedUrl);
// 解码 URL
let decodedUrl = decodeURIComponent(encodedUrl);
console.log("解码后的 URL: " + decodedUrl);
encodeURIComponent:用于对 URL 中的参数值进行编码,确保特殊字符(如空格、&、= 等)被正确转义。它会将这些字符转换为百分号编码的形式(例如,空格会被编码为 %20)。
decodeURIComponent:用于对经过 encodeURIComponent 编码的字符串进行解码,恢复为原始字符串。
应用场景:当你需要在 URL 中传递包含特殊字符的参数时,使用 encodeURIComponent 可以确保 URL 的正确性和可读性。
上一篇:js urlencode编码
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站