Webdevtoolsonline.com Home About Contact
Google

URL encode and decode functions for javascript

The Javascript function "escape" is often used for URL encoding, but it is not to the exact same thing as URL encoding. If you need to have the real thing in your script, feel free to use the script below.

 

function mURLEncode(sInput) {
var sAllowedChars='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'+
'abcdefghijklmnopqrstuvwxyz-_.!~*\'()';
var sHex='0123456789ABCDEF';
var sOutput='';
for (var i=0; i
var c=sInput.charAt(i);
if (c==' ') {
sOutput+='+';
} else if (sAllowedChars.indexOf(c)!=-1) {
sOutput+=c;
} else {
var charCode=c.charCodeAt(0);
if (charCode>255) {
alert('Sorry, no unicode support. Encoding aborted');
return false;
} else {
sOutput+='%';
sOutput+=sHex.charAt((charCode>>4)&0xF);
sOutput+=sHex.charAt(charCode&0xF);
}
}
}
return sOutput;
}

function mURLDecode(sInput) {
var sHex='0123456789ABCDEFabcdef';
var sOutput='';
var i=0;
while (i
var c=sInput.charAt(i);
if (c=='+') {
sOutput+=' ';
i++;
} else if (c=='%') {
if (i<(sInput.length-2) && sHex.indexOf(sInput.charAt(i+1))!=-1
&& sHex.indexOf(sInput.charAt(i+2))!=-1) {
sOutput+=unescape(sInput.substr(i,3) );
i+=3;
} else {
alert('Input contains invalid characters');
return false;
}
} else {
sOutput+=c;
i++;
}
}
return sOutput;
}

 

This website is hosted by Vendite.nl and is a silly old tweak from Menno Bieringa