Last active
June 23, 2020 14:09
-
-
Save cgwxyz/6053d51e8d7134dd2e30 to your computer and use it in GitHub Desktop.
lua urlencode/urldecode
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 encodeURI(str) | |
if (str) then | |
str = string.gsub (str, "\n", "\r\n") | |
str = string.gsub (str, "([^%w ])", | |
function (c) return string.format ("%%%02X", string.byte(c)) end) | |
str = string.gsub (str, " ", "+") | |
end | |
return str | |
end | |
function decodeURI(s) | |
if(s) then | |
s = string.gsub(s, '%%(%x%x)', | |
function (hex) return string.char(tonumber(hex,16)) end ) | |
end | |
return s | |
end |
Line 4 is not the right regex for url safe characters. This code will incorrectly % encode the characters .
_
-
~
even though they are already safe per https://tools.ietf.org/html/rfc3986#section-2.3. The correct one would be
str = string.gsub(str, "([^%w _ %- . ~])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should add this line at line 13 :
s = string.gsub(s, "+", " ")