前端JS中encodeURI和encodeURIComponent的区别?
在 JavaScript 中,encodeURI() 和 encodeURIComponent() 是用于对 URI 进行编码的两个方法,它们可以将 URI 中的特殊字符进行转义,以便在 URL 中安全地传输和显示。
-
encodeURI()方法用于对整个 URI 进行编码,除了常见的字符(字母、数字、-、_、.、!、~、*、'、(、))外,不会对其他字符进行编码。这意味着保留了一些特殊字符,如/、:、@、&等,不会被编码。该方法通常用于对整个 URL 进行编码,以确保 URL 的结构不被破坏。 -
encodeURIComponent()方法则用于对 URI 中的特定部分(如查询字符串参数值)进行编码。它会对所有非标准字符(包括常见字符)进行编码,确保所有字符都能在 URL 中安全传输。这意味着即使是常见的字符如/、:、@、&等也会被编码成%xx的形式。
下面是一个简单的示例展示了 encodeURI() 和 encodeURIComponent() 的用法:
let uri = "https://www.example.com/search?q=hello world&category=news";
let encodedUri = encodeURI(uri);
let encodedComponent = encodeURIComponent(uri);
console.log(encodedUri); // 输出:https://www.example.com/search?q=hello%20world&category=news
console.log(encodedComponent); // 输出:https%3A%2F%2Fwww.example.com%2Fsearch%3Fq%3Dhello%20world%26category%3Dnews
总的来说,encodeURI() 用于编码整个 URI,而 encodeURIComponent() 则用于编码 URI 中的特定部分,根据具体需求选择合适的方法进行编码。

浙公网安备 33010602011771号