Reputation: 165
looking for elixir way to encode a uri component ie
javascript
encodeURI("&")
"&"
encodeURIComponent("&")
"%26"
Elixir
URI.encode("&")
"&"
pry(11)> URI.encode_query(%{k: " & "})
basically I want encode_query but not have to do key value map and also encode spaces as %20, not +
"+k=%26+"
Upvotes: 2
Views: 1258
Reputation: 1929
URI.encode/2
accepts second optional argument - a function to determine whether or not skip encode a char. So we can use the function that returns false (not skip) for any char:
URI.encode("&", fn(_) -> false end)
"%26"
Upvotes: 0
Reputation: 165
found solution, uri.encode has default argument of
def char_unescaped?(char) when char in 0..0x10FFFF do
char_reserved?(char) or char_unreserved?(char)
end
for the second argument, by passing char_unreserved, the function will now encode reserved characters
URI.encode(" & ", &URI.char_unreserved?(&1))
"%20%26%20"
Upvotes: 6