如何使用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变量?
当前回答
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
其他回答
现代解决方案(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());
这个解决方案也在这里和这里提到。
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
编码URL字符串
var url = $(location).attr('href'); // Get the current URL
// Or
var url = 'folder/index.html?param=#23dd&noob=yes'; // Or specify one
var encodedUrl = encodeURIComponent(url);
console.log(encodedUrl);
// Outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes
有关详细信息,请转到jQuery编码/解码URL字符串。
我总是用这个来编码URL。这是完全安全的,因为它将对每个字符进行编码,即使它不必进行编码。
function urlEncode(text) {
let encoded = '';
for (let char of text) {
encoded += '%' + char.charCodeAt(0).toString(16);
}
return encoded;
}
不要忘记用/g标志替换所有编码的“”
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl).replace(/%20/g,'+');