如何使用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变量?
当前回答
我用普通JavaScript做了类似的尝试:
function fixedEncodeURIComponent(str){
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
其他回答
查看内置函数encodeURIComponent(str)和encodeURI(str)。在您的情况下,这应该有效:
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
我总是用这个来编码URL。这是完全安全的,因为它将对每个字符进行编码,即使它不必进行编码。
function urlEncode(text) {
let encoded = '';
for (let char of text) {
encoded += '%' + char.charCodeAt(0).toString(16);
}
return encoded;
}
使用fixedEncodeURIComponent函数严格遵守RFC 3986:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
let name=`bbb`;params=“name=${name}”;var myOtherUrl=`http://example.com/index.html?url=${encodeURIComponent(params)}`;console.log(myOtherUrl);
现在在ES6中使用backtick来编码URL
试试这个-https://bbbootstrap.com/code/encode-url-javascript-26885283
我建议使用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