Peter Hoffmann

CoffeeScript String Interpolation with HTML Escaping

CoffeeScript string interpolation, and how to combine it with HTML escaping.

This post is from 2012. Some of the content may be outdated.

Coffeescript supports ruby-style string interpolation inside double quotes.

author = "Wittgenstein"
quote  = "A picture is a fact. -- #{ author }"

# A picture is a fact. -- Wittgenstein

As the string interpolation is not limited to simple variable substitution, it's easy to define an escaping function and use it inside the string interpolation

escape = (s) -> (''+s).replace(/&/g, '&amp;').replace(/</g, '&lt;')
        .replace(/>/g, '&gt;').replace(/"/g, '&quot;')
        .replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;')

author = '<blink>Wittgenstein</blink>'
quote  = "A picture is a fact. -- #{ escape author }"

#A picture is a fact. -- &lt;blink&gt;Wittgenstein&lt;&#x2F;blink&gt;