I was just testing something with AJAX and I found that on success if I alert
alert(decodeURI('%'));
or
alert(encodeURIComponent('%'));
the browser errors out with the following code.
$.ajax({
type: "POST",
url: "some.php",
data: "",
success: function(html){
alert(decodeURIComponent('%'));
// alert(decodeURI('%'));
}
});
If I use any other string it works just fine.
Is it something that I missed?
The endless-loop or lock up may be due to a bug in jquery.
You can set a breakpoint in jquery at a point which is likely causing the 'lock-up'.
Decode doesn't make sense with just
%
provided, aspercent-encoding
is followed by alphanumericals referring to a given character in the ASCII table, and should normally yield an URIError in Opera, Chrome, FF.Use the browser built in function
encodeURI
if you are looking for the 'url-encoded' notation of the percent-character:Recently a
decodeURIComponent
in my code tripped over the ampersand%
and googling led me to this question.Here's the function I use to handle
%
which is shorter than the version of Ilia:It
%
NOT followed by a two-digit number with%25
It also works with the other samples around here:
decodeURIComponentSafe("%%20Visitors") // % Visitors
decodeURIComponentSafe("%Directory%20Name%") // %Directory Name%
decodeURIComponentSafe("%") // %
decodeURIComponentSafe("%1") // %1
The point is that if you use single
%
it breaks the logic ofdecodeURIComponent()
function as it expects two-digit data-value followed right after it, for example%20
(space).There is a hack around. We need to check first if the
decodeURIComponent()
actually can run on given string and if not return the string as it is.Example:
Running:
will result in
Uncaught URIError: URI malformed
errorwhile:
will return the initial string.
In case you would want to have a fixed/proper URI and have
%
turned into%25
you would have to pass1
as additional parameter to the custom function:Chrome barfs when trying from the console. It gives an URIError: URI malformed. The % is an escape character, it can't be on its own.
Because URL is malformed (% is not a url)
encodeURIComponent()
worksThe problem here is you're trying to decode the
%
. This is not a valid encoded string. I think you want to encode the%
instead.