如何使用JavaScript安全地编码URL,以便将其放入GET字符串中?
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
我假设您需要在第二行编码myUrl变量?
如何使用JavaScript安全地编码URL,以便将其放入GET字符串中?
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
我假设您需要在第二行编码myUrl变量?
当前回答
表演
今天(2020.06.12),我在浏览器Chrome 83.0、Safari 13.1和Firefox 77.0的macOS v10.13.6(High Sierra)上对所选解决方案进行了速度测试。这一结果对于大规模URL编码非常有用。
结论
encodeURI(B)似乎最快,但不建议用于URLescape(A)是一种快速的跨浏览器解决方案MDN推荐的解决方案F为中速解决方案D最慢
细节
对于解决方案A.BCDEF我进行了两次测试
对于短URL-50个字符-您可以在这里运行对于长URL-1M个字符-您可以在此处运行
函数A(url){返回转义符(url);}函数B(url){返回encodeURI(url);}函数C(url){返回encodeURIComponent(url);}函数D(url){返回新的URLSearchParams({url}).toString();}函数E(url){return encodeURIComponent(url).replace(/[!'()]/g,escape).replace(/\*/g,“%2A”);}函数F(url){return encodeURIComponent(url).replace(/[!'()*]/g,函数(c){return“%”+c.charCodeAt(0).toString(16);});}// ----------//测试// ----------var myUrl=“http://example.com/index.html?param=1&anotherParam=2";[A、B、C、D、E、F].forEach(f=>console.log(`${f.name}?url=${f(myUrl).replace(/^url=/,'')}`));此代码段仅显示所选解决方案的代码
Chrome的示例结果
其他回答
查看内置函数encodeURIComponent(str)和encodeURI(str)。在您的情况下,这应该有效:
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
什么是URL编码:
当URL中有特殊字符时,应对URL进行编码。例如:
console.log(encodeURIComponent('?notEncoded=&+'));
我们可以在这个例子中观察到,除了字符串notEncoded之外的所有字符都用%符号编码。URL编码也称为百分比编码,因为它用%转义所有特殊字符。然后在这个%符号之后,每个特殊字符都有一个唯一的代码
为什么我们需要URL编码:
某些字符在URL字符串中具有特殊值。例如?字符表示查询字符串的开头。为了在web上成功定位资源,必须区分字符是字符串的一部分还是URL结构的一部分。
如何在JavaScript中实现URL编码:
JavaScript提供了一系列内置实用程序函数,我们可以使用这些函数轻松地对URL进行编码。有两个方便的选项:
encodeURIComponent():将URI的一个组件作为参数,并返回编码的URI字符串。encodeURI():将URI作为参数并返回编码的URI字符串。
示例和警告:
注意不要将整个URL(包括方案,例如https://)传递到encodeURIComponent()中。这实际上可以将其转换为不起作用的URL。例如:
//对于整个URI,不要使用encodeURIComponent,它将转换///字符和URL不能正常工作console.log(encodeURIComponent(“http://www.random.com/specials&char.html"));//而是对整个URL使用encodeURIconsole.log(encodeURI(“http://www.random.com/specials&char.html"));
我们可以观察到,如果我们将整个URL放在encodeURIComponent中,正斜杠(/)也会转换为特殊字符。这将导致URL不再正常运行。
因此(顾名思义)使用:
encodeURIComponent位于要编码的URL的特定部分。要编码的整个URL上的encodeURI。
坚持使用encodeURIComponent()。函数encodeURI()不需要对URL中具有语义重要性的许多字符进行编码(例如“#”、“?”和“&”)。escape()已被弃用,并且不必对“+”字符进行编码,因为这些字符将在服务器上被解释为已编码的空格(正如其他人在这里指出的,不正确地对非ASCII字符进行URL编码)。
其他地方对encodeURI()和encodeURIComponent()之间的区别有很好的解释。如果您希望对某个内容进行编码,以便它可以安全地作为URI的一个组件(例如作为查询字符串参数)包含,则需要使用encodeURIComponent()。
编码URL字符串
var url = $(location).attr('href'); // Get the current URL
// Or
var url = 'folder/index.html?param=#23dd&noob=yes'; // Or specify one
var encodedUrl = encodeURIComponent(url);
console.log(encodedUrl);
// Outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes
有关详细信息,请转到jQuery编码/解码URL字符串。
我总是用这个来编码URL。这是完全安全的,因为它将对每个字符进行编码,即使它不必进行编码。
function urlEncode(text) {
let encoded = '';
for (let char of text) {
encoded += '%' + char.charCodeAt(0).toString(16);
}
return encoded;
}