如何使用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变量?
当前回答
我建议使用qs-npm包:
qs.stringify({a:"1=2", b:"Test 1"}); // gets a=1%3D2&b=Test+1
它更容易与JavaScript对象一起使用,并且为所有参数提供了正确的URL编码。
如果您使用jQuery,我会使用$.param方法。它对一个对象进行URL编码,将字段映射到值,这比对每个值调用转义方法更容易读取。
$.param({a:"1=2", b:"Test 1"}) // Gets a=1%3D2&b=Test+1
其他回答
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', '+');
}
您有三个选项:
escape()不会编码:@*/+encodeURI()不会编码:~@#$&*()=:/,;?+'encodeURIComponent()不会编码:~*()'
但在您的情况下,如果要将URL传递到其他页面的GET参数中,则应该使用escape或encodeURIComponent,而不是encodeURI。
有关详细讨论,请参阅堆栈溢出问题最佳实践:转义或encodeURI/encodeURIComponent。
使用fixedEncodeURIComponent函数严格遵守RFC 3986:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
我认为在2022年,为了真正安全,您应该始终考虑使用URL()接口构建URL。它将为您完成大部分工作。所以,说到你的代码,
常量baseURL='http://example.com/index.html';const myUrl=新URL(baseURL);myUrl.searchParams.append(“参数”,“1”);myUrl.searchParams.append(“otherParam”,“2”);const myOtherUrl=新URL(baseURL);myOtherUrl.searchParams.append('url',myUrl.href);console.log(myUrl.href);//输出:http://example.com/index.html?param=1&anotherParam=2console.log(myOtherUrl.href);//输出:http://example.com/index.html?url=http%3A%2F%2Fexample.com%2Findex.html%3Fparam%3D1%26anotherParam%3D2console.log(myOtherUrl.searchParams.get('url'));//输出:http://example.com/index.html?param=1&anotherParam=2
或
const params = new URLSearchParams(myOtherUrl.search);
console.log(params.get('url'));
// Outputs: http://example.com/index.html?param=1&anotherParam=2
像这样的东西肯定不会失败。
为了防止双重编码,最好在编码之前解码URL(例如,如果您处理的是用户输入的URL,可能已经编码)。
假设我们有abc%20xyz 123作为输入(一个空格已编码):
encodeURI("abc%20xyz 123") // Wrong: "abc%2520xyz%20123"
encodeURI(decodeURI("abc%20xyz 123")) // Correct: "abc%20xyz%20123"