Search

Dark theme | Light theme

July 8, 2020

Clojure Goodness: Replacing Characters In A String With escape Function

The clojure.string namespace contains a lot of useful functions to work with string values. The escape function can be used to replace characters in a string with another character. The function accepts as first argument the string value and the second argument is a map. The map has characters as key that need to be replaced followed by the value it is replaced with. For example the map {\a 1 \b 2} replaces the character a with 1 and the character b with 2.

In the following example code we use the escape function in several cases:

(ns mrhaki.string.escape-string
  (:require [clojure.string :as str]
            [clojure.test :refer [is]]))

(is (= "I 10v3 C10jur3"
       (str/escape "I love Clojure" {\o 0 \e 3 \l 1})))

(is (= "mrHAKI" 
       (str/escape "mrhaki" {\h "H" \a "A" \k "K" \i "I" \x "X"})))

(def html-escaping {(char 60) "<" (char 62) ">" (char 38) "&"})
(is (= "<h1>Clojure & Groovy rocks!</h1>"
       (str/escape "<h1>Clojure & Groovy rocks!</h1>" html-escaping)))

(is (= "Special chars: \\t \\n"
       (str/escape "Special chars: \t \n" char-escape-string)))

Written with Clojure 1.10.1.