Created
August 23, 2013 19:51
-
-
Save QuestionDevelopment/6323289 to your computer and use it in GitHub Desktop.
URL encode/decode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function URLEncode (clearString) { | |
var output = ''; | |
var x = 0; | |
clearString = clearString.toString(); | |
var regex = /(^[a-zA-Z0-9_.]*)/; | |
while (x < clearString.length) { | |
var match = regex.exec(clearString.substr(x)); | |
if (match != null && match.length > 1 && match[1] != '') { | |
output += match[1]; | |
x += match[1].length; | |
} else { | |
if (clearString[x] == ' ') | |
output += '+'; | |
else { | |
var charCode = clearString.charCodeAt(x); | |
var hexVal = charCode.toString(16); | |
output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase(); | |
} | |
x++; | |
} | |
} | |
return output; | |
} | |
function URLDecode (encodedString) { | |
var output = encodedString; | |
var binVal, thisString; | |
var myregexp = /(%[^%]{2})/; | |
while ((match = myregexp.exec(output)) != null | |
&& match.length > 1 | |
&& match[1] != '') { | |
binVal = parseInt(match[1].substr(1),16); | |
thisString = String.fromCharCode(binVal); | |
output = output.replace(match[1], thisString); | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment