在 JavaScript 中,用于编码 URL 敏感的特殊字符的方法实际上是 encodeURIComponent()
,而不是 encodeURL()
。encodeURIComponent()
方法用于对 URL 的组成部分进行编码,以确保它们可以安全地用于 URL 中。
encodeURIComponent()
方法
encodeURIComponent()
方法会将字符串作为参数,并返回一个经过编码的字符串,其中所有的特殊字符都被替换为 %
符号加上两位十六进制数。这适用于 URL 的各个组成部分,如路径、查询参数等。
const url = 'https://example.com/search?q=hello+world&category=sports';
const encodedUrl = 'https://example.com/search?q=' + encodeURIComponent('hello world') + '&category=' + encodeURIComponent('sports');
console.log(encodedUrl); // 输出: https://example.com/search?q=hello%20world&category=sports