如何使用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()是最好的方法。
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', '+');
}
其他回答
您可以使用ESAPI库并使用以下函数对URL进行编码。该函数确保在对其余文本内容进行编码时,“/”不会因编码而丢失:
function encodeUrl(url)
{
String arr[] = url.split("/");
String encodedUrl = "";
for(int i = 0; i<arr.length; i++)
{
encodedUrl = encodedUrl + ESAPI.encoder().encodeForHTML(ESAPI.encoder().encodeForURL(arr[i]));
if(i<arr.length-1) encodedUrl = encodedUrl + "/";
}
return url;
}
我建议使用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
我认为在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
像这样的东西肯定不会失败。
使用fixedEncodeURIComponent函数严格遵守RFC 3986:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
不应直接使用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);
});
}