Skip to content

Instantly share code, notes, and snippets.

@liukun liukun/url-encode.lua
Last active Nov 19, 2019

Embed
What would you like to do?
local char_to_hex = function(c)
return string.format("%%%02X", string.byte(c))
end
local function urlencode(url)
if url == nil then
return
end
url = url:gsub("\n", "\r\n")
url = url:gsub("([^%w ])", char_to_hex)
url = url:gsub(" ", "+")
return url
end
local hex_to_char = function(x)
return string.char(tonumber(x, 16))
end
local urldecode = function(url)
if url == nil then
return
end
url = url:gsub("+", " ")
url = url:gsub("%%(%x%x)", hex_to_char)
return url
end
-- ref: https://gist.github.com/ignisdesign/4323051
-- ref: http://stackoverflow.com/questions/20282054/how-to-urldecode-a-request-uri-string-in-lua
-- to encode table as parameters, see https://github.com/stuartpb/tvtropes-lua/blob/master/urlencode.lua
@callicoder

This comment has been minimized.

Copy link

callicoder commented Dec 10, 2018

Awesome! Thanks for the gist. URLs can also be encoded online using URLEncoder.io tool.

@DanielVukelich

This comment has been minimized.

Copy link

DanielVukelich commented Jun 27, 2019

Line 10 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 _ %- . ~])", char_to_hex)

@DeltaNedas

This comment has been minimized.

Copy link

DeltaNedas commented Aug 16, 2019

you forgot to escape some patterns too bro
str = string.gsub(str, "([^%w _%%%-%.~])", char_to_hex)
If it isnt alphanumeric, a space, a % sign, a -, a . or a ~ it will decode

@kids0407

This comment has been minimized.

Copy link

kids0407 commented Oct 22, 2019

Thanks for the gist. URLs can also be decoded/encoded online using UrlTools.org tool.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.