如何使用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()。函数encodeURI()不需要对URL中具有语义重要性的许多字符进行编码(例如“#”、“?”和“&”)。escape()已被弃用,并且不必对“+”字符进行编码,因为这些字符将在服务器上被解释为已编码的空格(正如其他人在这里指出的,不正确地对非ASCII字符进行URL编码)。

其他地方对encodeURI()和encodeURIComponent()之间的区别有很好的解释。如果您希望对某个内容进行编码,以便它可以安全地作为URI的一个组件(例如作为查询字符串参数)包含,则需要使用encodeURIComponent()。

encodeURIComponent()是最好的方法。

var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

但是您应该记住,与PHP版本urlencode()有一些小的不同,正如@CMS所提到的,它不会对每个字符进行编码。伙计们在http://phpjs.org/functions/urlencode/使JavaScript等效于phpencodes():

function urlencode(str) {
  str = (str + '').toString();

  // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
  // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
  return encodeURIComponent(str)
    .replace('!', '%21')
    .replace('\'', '%27')
    .replace('(', '%28')
    .replace(')', '%29')
    .replace('*', '%2A')
    .replace('%20', '+');
}

什么是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()。

看看RFC3986:统一资源标识符(URI):通用语法

sub-delims=“!”/“$”/“&”/“'”/“(”/“)”/ "*" / "+" / "," / ";" / "="保留字符的目的是提供一组可与URI中的其他数据区分的分隔字符。

这些来自RFC3986中URI定义的保留字符不会被encodeURIComponent()转义。

MDN Web文档:encodeURIComponent()

为了更严格地遵守RFC 3986(保留!、'、(、)和*),即使这些字符没有正式的URI分隔用途,也可以安全地使用以下字符:

使用MDN Web Docs功能。。。

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

表演

今天(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的示例结果