// URL编码示例代码
// 使用 encodeURIComponent 对字符串进行编码
let url = "https://example.com/search?q=JavaScript URL 编码";
let encodedUrl = encodeURIComponent(url);
console.log(encodedUrl);
// 输出: https%3A%2F%2Fexample.com%2Fsearch%3Fq%3DJavaScript%20URL%20%E7%BC%96%E7%A0%81
// 使用 encodeURI 对整个URL进行编码,保留协议、域名等部分不被编码
let fullUrl = "https://example.com/search?q=JavaScript URL 编码";
let encodedFullUrl = encodeURI(fullUrl);
console.log(encodedFullUrl);
// 输出: https://example.com/search?q=JavaScript%20URL%20%E7%BC%96%E7%A0%81
// 解码使用 decodeURIComponent 或 decodeURI
let decodedUrl = decodeURIComponent(encodedUrl);
console.log(decodedUrl);
// 输出: https://example.com/search?q=JavaScript URL 编码
let decodedFullUrl = decodeURI(encodedFullUrl);
console.log(decodedFullUrl);
// 输出: https://example.com/search?q=JavaScript URL 编码
encodeURIComponent:对整个字符串进行编码,包括协议、域名、路径和查询参数。适用于对单独的查询参数或片段进行编码。encodeURI:对整个URL进行编码,但不会对协议、域名等部分进行编码,只对查询参数和路径中的特殊字符进行编码。适用于对完整的URL进行编码。decodeURIComponent 和 decodeURI:分别用于解码 encodeURIComponent 和 encodeURI 编码后的字符串。上一篇:js 解析url
下一篇:js 获取url 参数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站