2014-12-13 Escaping madness

I was writing a part of my Org-edu-HTML tool, and needed to generate a piece of JavaScript declaring a string variable. The string is given by the user and as such is assumed to contain things like Robert'); DROP TABLE Students;-- (well, not exactly that in this case, but if you pass a user-defined string to (lambda (string) (format "var crazyString='%s';" string)), you are asking for trouble. What needed to be done was (if I get all this stuff correctly) escaping <, >, &, but also the quotes: ', " (just in case I decided to change var crazyString = '...'; to var crazyString = "...";) and – importantly – the backslash. While writing the function to do this (which I based on org-html-encode-plain-text, which incidentally is a very nice example of functional programming), I wrote this funny-looking expression, which at a first glance does nothing:

(replace-regexp-in-string "\\\\" "\\\\" text t t)

It should be more or less clear what it does: in the former string, we have a regex consisting of two backslashes (since backslashes in string literals in Elisp have to be escaped); this way, this regex matches a single backslash (since backslashes in Elisp regexen have to be escaped). The latter string is literal (=not a regex), so it consists of two backslashes (again), which are then interpreted by JavaScript as one backslash (since backslashes in JS strings have to escaped).


CategoryEnglish, CategoryBlog, CategoryEmacs, CategoryOrgMode