function fixedEncodeURI(str) { const prepURL = new URL(str); const origin = prepURL.origin; let raw = str; let decoded = decodeURI(str); while (raw !== decoded) { decoded = decodeURI(decoded); raw = decodeURI(raw); } justPath = decoded.replace(origin, ''); let output = origin + encodeURIComponent(justPath).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); return output.replace(/%3F/g, '?').replace(/%3D/g, '=').replace(/%26/g, '&'); } // fixedEncodeURI('http://foo.bar/foo/bar/ツ') returns http://foo.bar%2Ffoo%2Fbar%2F%E3%83%84