I’ve recently started using CoffeeScript’s triple quote syntax for escaping html within JavaScript rather than RoR’s escape_javascript(). But I was wondering if there were any major differences between the two that I should know about before switching.
Are there any benefits of one over the other?
Triple quotes in CoffeeScript don’t escape anything, they just handle interpolation, strip off some leading whitespace, and convert embedded newlines to
\n; of course,escape_javascriptdoesn’t do anything with HTML either. For example:becomes:
Single quotes have no meaning inside double quoted strings so CoffeeScript does nothing with them, double quotes are escaped though. But, an embedded triple quote will be interpreted as the end of the triple quoted string so, if your ERB came before your CoffeeScript to JavaScript translation, you could run into some trouble.
I would recommend against dropping
escape_javascriptin favor of throwing raw strings into CoffeeScript triple-quoted strings. If you really want to use triple-quoted strings then you’d do both:but that would be a pointless use of
"""since"""andescape_javascriptdo pretty much the same thing (except that"""will be confused by an embedded"""of course).