2

looking for elixir way to encode a uri component ie javascript encodeURI("&") "&" encodeURIComponent("&") "%26" Elixir URI.encode("&") "&" pry(11)> URI.encode_query(%{k: " & "})
"+k=%26+"
basically I want encode_query but not have to do key value map and also encode spaces as %20, not +

crododile
  • 145
  • 12

2 Answers2

4

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"

crododile
  • 145
  • 12
0

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"
Oleksandr Avoiants
  • 1,889
  • 17
  • 24