In clojure, how to write a function that applies several string replacements?

Implementing @kotarak's advice using replace, reduce and partition:

(defn replace-several [content & replacements]
      (let [replacement-list (partition 2 replacements)]
        (reduce #(apply string/replace %1 %2) content replacement-list)))
; => (replace-several "abc" #"a" "c" #"b" "l" #"c" "j")
  "jlj"

So you have replace, reduce and partition. From these building blocks you can build your replace-several.


Here is another shot but that has different output results, this one uses the regex engine features so it potentially may be faster, also the interface is different, since it maps keys to replacement strings. I provide this in case it may be useful to someone with a similar question.

(defn replace-map
  "given an input string and a hash-map, returns a new string with all
  keys in map found in input replaced with the value of the key"
  [s m]
  (clojure.string/replace s
              (re-pattern (apply str (interpose "|" (map #(java.util.regex.Pattern/quote %) (keys m)))))
          m))

So usage would be like so:

 (replace-map "abc" {"a" "c" "b" "l" "c" "j"})

=> "clj"

Tags:

Clojure