views:

226

answers:

2

I have noticed that IE7 does not url-encode querystring parameters retrieved from javascript, e.g:

var qs = location.search;

In Firefox, the parameters are encoded. How can I write IE-specific code to URL-encode the parameters in the same fashion as FireFox?

For example, in Firefox, this querystring:

?val=<script>

//gets rewritten as:

?val=%3Cscript%3E
A: 

You can use the escape function:

var qs = escape(location.search);
Sarfraz
Don't use `escape`, it doesn't support UTF-8 encoding. Use `encodeURIComponent` instead.
Andy E
@Andy: Thanks for sharing, i did not know about that :)
Sarfraz
+3  A: 

Normally, the correct function to URL-encode a string for use in part of a URL is encodeURIComponent. Don't use escape, which is an obsolescent non-standard custom encoding scheme unique to JavaScript. It looks like URL-parameter-encoding, but treats pluses and all non-ASCII characters differently. Put it together with a standard URL decoder and you get errors.

However, you shouldn't call encodeURIComponent over location.search if it's giving you bad characters like < or > (which shouldn't appear in a URL, but which IE allows you to enter), because it will double-encode characters that are already correctly encoded; for example a real %3C in the address (from if the user has followed a correctly-formed link to your site) will get mis-converted to %253C.

Fixing up ‘unsafe’ URL characters whilst leaving already-encoded characters alone is what the encodeURI function is for; try that (on all browsers, no need for sniffing). It's rarely used, but could be what you need. Otherwise, you're looking at an annoying regexp-and-hex-encoding-function replacement.

bobince
It's `encodeURI` rather than `encodeURL`.
Tim Down
You're right! I'm a fat-fingered fool.
bobince