如何使用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

其他回答

查看内置函数encodeURIComponent(str)和encodeURI(str)。在您的情况下,这应该有效:

var myOtherUrl = 
       "http://example.com/index.html?url=" + encodeURIComponent(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', '+');
}

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

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

我用普通JavaScript做了类似的尝试:

function fixedEncodeURIComponent(str){
    return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}