Wednesday, February 2, 2011

Encode a query string in javascript

encodeURIComponent will work. (You may or may not want the leading '?', depending on what the script is expecting.)

var c= 'd e'
var query= '?a=b&c='+encodeURIComponent(c);
var uri= 'http://www.example.com/script?query='+encodeURIComponent(query);
window
.location= uri;

Takes me to:

http://www.example.com/script?query=%3Fa%3Db%26c%3Dd%2520e

When you hover over that it may appear once-decoded in the browser's status bar, but you will end up in the right place.

escape/unescape() is the wrong thing for encoding query parameters, it gets Unicode characters and pluses wrong. There is almost never a case where escape() is what you really need.


No comments:

Post a Comment