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.