Urldecode string (LUA)
Sometimes, particularly when using LUA OpenResty, in may be necessary to url unencode/unescape a string, so that reserved characters are converted back to their literal representations. This is particularly useful as the value if ngx.var.arg_ variables are not automatically url unencoded
This snippet creates a function to do hex decode each character of a string
Similar To
- urldecode() PHP
- urllib.unquote() Python
- decodeURI() Javascript
Details
- Language: LUA
Snippet
local urldecode = function(url)
return (url:gsub("%%(%x%x)", function(x)
return string.char(tonumber(x, 16))
end))
end
Usage Example
local urldecode = function(url)
return (url:gsub("%%(%x%x)", function(x)
return string.char(tonumber(x, 16))
end))
end
local s='a%20b%20c'
print(urldecode(s))
-- a b c
-- Or to decode the query string value of argument 'foo' in OpenResty
ngx.print(urldecode(ngx.var.arg_foo))