Encode URL in JavaScript?

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 (e.g. "#", "?", 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 (e.g. as a query string parameter), you want to use encodeURIComponent().