Categories
encode javascript url urlencode

Encode URL in JavaScript?

2745

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?

5

3069

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);

11

1646

You have three options:

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

  • encodeURI() will not encode: [email protected]#$&*()=:/,;?+'

  • 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.

10

  • 86

    The character encoding used with escape is variable. Stick with encodeURI and encodeURIComponent, which use UTF-8.

    – erickson

    Dec 2, 2008 at 4:55

  • 7

    Be careful. That escape converts non-ASCII characters into its Unicode escape sequences, like %uxxx.

    – opteronn

    Mar 5, 2010 at 20:10


  • 4

    I am using encodeURIComponent and noticing it will not encode pipe characters |

    Jan 30, 2011 at 5:05

  • 15

    @kevzettler – why should it do that? The pipes aren’t of semantic importance in a URI.

    – nickf

    Jan 31, 2011 at 11:36

  • 4

    @GiovanniP: People who allow German, French, Japanese, Chinese, Arabic characters as input and pass theses parameters via GET or POST.

    – Tseng

    Sep 4, 2013 at 14:43

201

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().

0