如何使用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()和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字符串

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字符串。

这里是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>

我认为在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

像这样的东西肯定不会失败。

我建议使用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

我总是用这个来编码URL。这是完全安全的,因为它将对每个字符进行编码,即使它不必进行编码。

function urlEncode(text) {
    let encoded = '';
    for (let char of text) {
        encoded += '%' + char.charCodeAt(0).toString(16);
    }
    return encoded;
}