2

Suppose I've got an html document:

<html>test<html>

And I want to display that code in a browser. Then I'd create something like:

<html><body>
<pre>&lt;html&gt;test&lt;html&gt;</pre>
</body></html>

To make the gubbins in the middle I have a function:

(defn html-escape [string] 
  (str "<pre>" (clojure.string/escape string {\< "&lt;", \> "&gt;"}) "</pre>"))

which does the above transformation for me:

user> (html-escape "<html>test<html>")
"<pre>&lt;html&gt;test&lt;html&gt;</pre>"

My question is: is that good enough, or am I going to come across html that will make that transformation break?

And a secondary question might be: does clojure have this built in? I can't find it.

1 Answer 1

3

There are a few options:

  1. Roll your own.
  2. Use commons StringEscapeUtils
  3. If you're using hiccup, it comes with a function for this.

For #3, just use the h function in hiccup.core.

For #2, add [org.apache.commons/commons-lang3 "3.1"] to your dependencies, and then you can encode with

(org.apache.commons.lang3.StringEscapeUtils/escapeHtml4 "your string")

For #1, you can use the function hiccup uses. It's pretty small:

(defn escape-html
  "Change special characters into HTML character entities."
  [text]
  (.. ^String (as-str text)
    (replace "&"  "&amp;")
    (replace "<"  "&lt;")
    (replace ">"  "&gt;")
    (replace "\"" "&quot;")))

Any of these solutions are fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.