如何使用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
第二行的变量?
查看内置功能 encodeURIComponent(str)
和 encodeURI(str)
。
在你的情况下,这应该工作:
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
你有三个选择:
escape()
不会编码: @*/+
encodeURI()
不会编码: ~!@#$&*()=:/,;?+'
encodeURIComponent()
不会编码: ~!*()'
但在你的情况下,如果你想传递一个 网址 变成一个 GET
其他页面的参数,你应该使用 escape
要么 encodeURIComponent
, 但不是 encodeURI
。
请参阅Stack Overflow问题 最佳实践:escape,或encodeURI / encodeURIComponent 进一步讨论。
坚持 encodeURIComponent()
。功能 encodeURI()
不打算编码在URL中具有语义重要性的许多字符(例如“#”,“?”和“&”)。 escape()
不推荐使用,并且不打算编码“+”字符,这些字符将被解释为服务器上的编码空格(并且,正如其他人所指出的那样,不能对非ASCII字符进行正确的URL编码)。
有一个很好的 解释之间的区别 encodeURI()
和 encodeURIComponent()
别处。如果您想对某些内容进行编码,以便可以安全地将其作为URI的一个组件包含在内(例如作为查询字符串参数),那么您希望使用 encodeURIComponent()
。
就个人而言,我发现很多API都想用“+”代替“”,所以我使用以下内容:
encodeURIComponent(value).replace(/%20/g,'+');
escape
在不同的浏览器和不同的实现 encodeURI
不会对URI中的大多数字符进行编码(例如#和even /) - 它可以在完整的URI / URL上使用而不会破坏它。
注意:你使用encodeURIComponent 值 查询字符串(不是字段/值名称,绝对不是整个URL)。如果你以任何其他方式执行它,它将不会编码=,?,&等字符,可能会使您的查询字符串暴露。
例:
const escapedValue = encodeURIComponent(value).replace(/%20/g,'+');
const url = 'http://example.com/?myKey=' + escapedValue;
如果您使用的是jQuery,我会选择 $.param
方法。它对将对象映射到值的对象进行编码,这比在每个值上调用转义方法更容易阅读。
$.param({a:"1=2", b:"Test 1"}) // gets a=1%3D2&b=Test+1
要编码URL,如前所述,您有两个功能:
encodeURI()
和
encodeURIComponent()
两者之所以存在的原因是,第一个保留URL的风险是留下太多未转义的东西,而第二个则编码所需的一切。
使用第一个,您可以将新转义的URL复制到地址栏(例如),它可以工作。然而,你的未转义的'&'会干扰字段分隔符,'='会干扰字段名称和值,而'+'会看起来像空格。但是对于简单的数据,当你想保留你正在逃避的URL性质时,这是有效的。
第二个是你需要做的一切,以确保你的字符串中没有任何内容干扰URL。它会保留未转义的各种不重要的字符,以便URL保持尽可能不受干扰的人类可读性。以这种方式编码的URL将不再作为URL工作而不会取消它。
因此,如果您可以花时间,您总是希望使用encodeURIComponent() - 在添加名称/值对之前,使用此函数对名称和值进行编码,然后再将其添加到查询字符串中。
我很难想出使用encodeURI()的理由 - 我会把它留给更聪明的人。
encodeURIComponent()是要走的路。
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
但是你应该记住,与php版本urlencode()存在细微的差别,并且如提到的@CMS,它不会对每个char进行编码。伙计们 http://phpjs.org/functions/urlencode/ 使js等同于phpencode():
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(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.
replace(/\)/g, '%29')
.replace(/\*/g, '%2A')
.replace(/%20/g, '+');
}
我用普通的javascript试过类似的东西
function fixedEncodeURIComponent(str){
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}