views:

14895

answers:

4

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?

+2  A: 

Try looking into encodeURI() and decodeURI().

Zack Mulgrew
+32  A: 

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);
Buu Nguyen
cheers! that's what I was after!
nickf
I tried this since I had a problem passing hex colors threw javascript and encodeURIComponent solved my proble, thx alot
Roland
Its amazing how poorly encoding is documented all over. Thank You for your brief and concise answer.
jini
+30  A: 

You have 3 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.

CMS
The character encoding used with escape is variable. Stick with encodeURI and encodeURIComponent, which use UTF-8.
erickson
+1  A: 

be careful that escape converts non-ascii chars into its unicode escape sequences like %uxxx

opteronn