URIError: malformed URI sequence

Posted by
September 13, 2018

The point is that if you use single % it breaks the logic of decodeURIComponent() function as it expects two-digit data-value followed right after it, for example, %20 (space). There is a solution to this. We need to check first if the decodeURIComponent() actually can run on given string and if not return the string as it is.

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;
}

 

read more