form-encode & form-decode

This commit is contained in:
Tommi Reiman 2018-08-01 18:57:17 +03:00
parent 303b124973
commit 6c23a5562a
2 changed files with 29 additions and 0 deletions

View file

@ -201,6 +201,23 @@
s)
:cljs (js/decodeURIComponent s))))
(defn form-encode [s]
(if s
#?(:clj (-> s
(str/replace #"[^A-Za-z0-9\!'\(\)\*_~.-\\\ ]+" percent-encode)
(^String .replace " " "+"))
:cljs (str/replace (js/encodeURIComponent s) "%20" "+"))))
(defn form-decode [s]
(if s
#?(:clj (let [s (if (.contains ^String s "+")
(.replace ^String s "+" " ")
s)]
(if (.contains ^String s "%")
(URLDecoder/decode s "UTF-8")
s))
:cljs (js/decodeURIComponent (str/replace s "+" " ")))))
(defprotocol IntoString
(into-string [_]))

View file

@ -157,3 +157,15 @@
"a//" "a//"
"/path/%C2%ABk%C3%BC%C3%9F%C3%AE%C2%BB" "/path/«küßî»"
"/path/%E2%80%9C%D0%8C%CF%8D%D0%91%D0%87%E2%80%9D" "/path/“ЌύБЇ”"))
(deftest form-encode-test
(are [in out]
(= out (impl/form-encode in))
"+632 905 123 4567" "%2B632+905+123+4567"))
(deftest form-decode-test
(are [in out]
(= out (impl/form-decode in))
"%2B632+905+123+4567" "+632 905 123 4567"))