Encode URL in JavaScript?

How do you safely encode a URL using JavaScript such that it can be put into a GET string?

var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;

I assume that you need to encode the myUrl variable on that second line?


Check out the built-in function encodeURIComponent(str) and encodeURI(str) .
In your case, this should work:

var myOtherUrl = 
       "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

You have three options:

  • escape() will not encode: @*/+

  • encodeURI() will not encode: ~!@#$&*()=:/,;?+'

  • encodeURIComponent() will not encode: ~!*()'

  • But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent , but not encodeURI .

    See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.


    Stick with encodeURIComponent() . The function encodeURI() does not bother to encode many characters that have semantic importance in URLs (eg "#", "?", and "&"). escape() is deprecated, and does not bother to encode "+" characters, which will be interpreted as encoded spaces on the server (and, as pointed out by others here, does not properly URL-encode non-ASCII characters).

    There is a nice explanation of the difference between encodeURI() and encodeURIComponent() elsewhere. If you want to encode something so that it can safely be included as a component of a URI (eg as a query string parameter), you want to use encodeURIComponent() .

    链接地址: http://www.djcxy.com/p/686.html

    上一篇: 为什么我不应该使用mysql

    下一篇: 在JavaScript中编码URL?