Peter Hoffmann on Stackoverflow @peterhoffmann on twitter Peter Hoffmann on Facebook Contact me per email Subscribe to Atom Feed

Peter Hoffmann

Software Engineer
prev page next page

CoffeeScript String Interpolation with HTML Escaping

Posted on July 31, 2012

Coffescript 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, '&').replace(/</g, '<')
        .replace(/>/g, '>').replace(/"/g, '"')
        .replace(/'/g, ''').replace(/\//g,'/')

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

#A picture is a fact. -- <blink>Wittgenstein</blink>