ClojureDocs

Nav

Namespaces

escape

clojure.string

Available since 1.2
  • (escape s cmap)
Return a new string, using cmap to escape each character ch
 from s as follows:
 
 If (cmap ch) is nil, append ch to the new string.
 If (cmap ch) is non-nil, append (str (cmap ch)) instead.
4 Examples
;; There should be no space between the \ and the &, but I don't know how
;; to create that in an example yet.
user=> (clojure.string/escape "I want 1 < 2 as HTML, & other good things."
               {\< "&lt;", \> "&gt;", \& "&amp;"})
"I want 1 &lt; 2 as HTML, &amp; other good things."
(ns test1.core
  (:require [clojure.string :as str]))

(def text1 "Hello Clojure World!")

;; Escape each character '!'
(str/escape text1 {\! "!!!"})
;; => "Hello Clojure World!!!"

;; Escape each space character
(str/escape text1 {\ "-"})
;; => "Hello-Clojure-World!"

;; Escape each characters '!' or space
(str/escape text1 {\! "!!!" \ "-"})
;; => "Hello-Clojure-World!!!"
;; Note it correctly handles the case where a replacement string contains
;; a char that’s in the replacement map:

(clojure.string/escape "123" {\1 "2"  \2 "3"  \3 "4"})
;; => "234"

(clojure.string/escape "ab" {\a "b"  \b "a"})
;; => "ba"
;; Escape can be called with a function as the second argument.

(defn convert [val]
  (case val
    \a \B
    \b \A
    \C))

(clojure.string/escape "ab" convert)
;; => "BA"

(clojure.string/escape "ak" convert)
;; => BC
See Also
No see-alsos for clojure.string/escape
0 Notes
No notes for escape