The fact is that if you use a single % , it interrupts the logic of the decodeURIComponent() function, since it expects that a double-digit data value will be displayed immediately after it, for example %20 (space).
There is a hack. First you need to check whether decodeURIComponent() can actually be executed on a given line and if you do not return the line as is.
Example:
function decodeURIComponentSafe(uri, mod) { var out = new String(), arr, i = 0, l, x; typeof mod === "undefined" ? mod = 0 : 0; arr = uri.split(/(%(?:d0|d1)%.{2})/); for (l = arr.length; i < l; i++) { try { x = decodeURIComponent(arr[i]); } catch (e) { x = mod ? arr[i].replace(/%(?!\d+)/g, '%25') : arr[i]; } out += x; } return out; }
Duration:
decodeURIComponent("%Directory%20Name%")
will result in an Uncaught URIError: URI malformed error Uncaught URIError: URI malformed
but
decodeURIComponentSafe("%Directory%20Name%") // %Directory%20Name%
will return the original string.
If you want to have a fixed / correct URI and % turn into %25 , you need to pass 1 as an additional parameter for the custom function:
decodeURIComponentSafe("%Directory%20Name%", 1) // "%25Directory%20Name%25"
Ilia Rostovtsev
source share