如何使用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变量?
当前回答
使用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);
});
}
现代解决方案(2021)
自从编写了其他答案后,就引入了URLSearchParams API。它可以这样使用:
const queryParams = { param1: 'value1', param2: 'value2' }
const queryString = new URLSearchParams(queryParams).toString()
// 'param1=value1¶m2=value2'
它还编码非URL字符。
对于您的具体示例,您可以这样使用:
常量myUrl=“http://example.com/index.html?param=1&anotherParam=2";const myOtherUrl=新URL(“http://example.com/index.html");myOtherUrl.search=新URLSearchParams({url:myUrl});console.log(myOtherUrl.toString());
这个解决方案也在这里和这里提到。
这里是encodeURIComponent()和decodeURIComponent()JavaScript内置函数的现场演示:
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width: 30%;
height: 100px;
}
</style>
<script>
// Encode string to Base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// Decode Base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
我总是用这个来编码URL。这是完全安全的,因为它将对每个字符进行编码,即使它不必进行编码。
function urlEncode(text) {
let encoded = '';
for (let char of text) {
encoded += '%' + char.charCodeAt(0).toString(16);
}
return encoded;
}
查看内置函数encodeURIComponent(str)和encodeURI(str)。在您的情况下,这应该有效:
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);