javascript中encodeURI和decodeURI方法
封面图
•
2025-12-16
•
JavaScript
247
0
0
0
在 JavaScript 中,`encodeURI()` 和 `decodeURI()` 是用于处理 URI(统一资源标识符)的两个常用方法。它们主要用于对 URI 进行编码和解码,以确保 URI 在传输过程中不会出现格式错误或被误解。 --- ## 一、`encodeURI()` ### 作用: 将一个完整的 URI 字符串进行编码,使其符合 URI 的语法要求。 ### 使用场景: 当你需要构建一个 URI(如 URL),并且其中包含特殊字符(如空格、#、& 等),可以使用 `encodeURI()` 对整个 URI 进行编码。 ### 示例: ```javascript let uri = "https://example.com/search?q=hello world"; let encodedUri = encodeURI(uri); console.log(encodedUri); // 输出: https://example.com/search?q=hello%20world ``` ### 注意: - `encodeURI()` **不会**对以下字符进行编码: - `A-Z a-z 0-9 : / ? # [ ] @ ! $ & ' ( ) * + , - . ; = _ ~` - 它适用于整个 URI,而不是其中的某个部分(如查询参数)。 --- ## 二、`decodeURI()` ### 作用: 将经过 `encodeURI()` 编码的 URI 字符串还原为原始字符串。 ### 使用场景: 当从 URL 中获取到经过编码的 URI 时,可以用 `decodeURI()` 来还原它。 ### 示例: ```javascript let encodedUri = "https://example.com/search?q=hello%20world"; let decodedUri = decodeURI(encodedUri); console.log(decodedUri); // 输出: https://example.com/search?q=hello world ``` --- ## 三、与 `encodeURIComponent()` 和 `decodeURIComponent()` 的区别 | 方法 | 用途 | 是否对 URI 的某些部分编码 | |------------------|--------------------------------|----------------------------| | `encodeURI()` | 编码整个 URI | ✅ 不编码保留字符 | | `decodeURI()` | 解码整个 URI | ✅ 解码所有编码过的字符 | | `encodeURIComponent()` | 编码 URI 的某一部分(如查询参数) | ❌ 编码所有字符(除了保留字符) | | `decodeURIComponent()` | 解码 URI 的某一部分 | ✅ 解码所有编码过的字符 | --- ## 四、示例对比 ```javascript let param = "hello world & test"; let encodedParam = encodeURIComponent(param); console.log(encodedParam); // 输出: hello%20world%20%26%20test let decodedParam = decodeURIComponent(encodedParam); console.log(decodedParam); // 输出: hello world & test ``` --- ## 五、总结 | 方法 | 用途 | 适用场景 | |--------------|------------------------------|------------------------------| | `encodeURI()` | 编码整个 URI | 构建完整 URL 时使用 | | `decodeURI()` | 解码整个 URI | 获取完整 URL 并还原其内容时使用 | | `encodeURIComponent()` | 编码 URI 的某一部分(如参数) | 处理 URL 查询参数时使用 | | `decodeURIComponent()` | 解码 URI 的某一部分 | 处理 URL 查询参数时使用 | --- 如果你有具体的使用场景或例子,我可以帮你进一步分析!
上一篇:
js获取地址中get参数
下一篇:
layer加载遮罩层使用 Ajax Loading Demo
标题录入,一次不能超过6条
留言
评论