2

It seems that my question should be common knowledge, and I thought I knew it (at some point in the distant past), but the answer escapes me tonight. I'd like to take a string like "foo" and programmatically convert it to "\"foo\"". Is there a built-in function for that?

I realize I can (concat "\"" "foo" "\""), but I thought there is probably an existing function that does this.

lawlist
  • 19,106
  • 5
  • 38
  • 120
  • You're not adding escaped double quote, only normal double quotes. They look escaped because that's how Emacs string syntax work. – YoungFrog Apr 11 '17 at 07:01
  • If you need any sort of protection against injection, this is not the way to do it. Could you give more context? – YoungFrog Apr 11 '17 at 07:03

1 Answers1

7

You might be thinking of prin1-to-string:

(prin1-to-string "foo")
=> "\"foo\""

You probably need some protection though (ensure it's a string, strip text properties, etc.), because you'll get more than you bargained for if you try it with a propertized string:

(prin1-to-string (propertize "foo" 'bar "baz"))
=> "#(\"foo\" 0 3 (bar \"baz\"))"

In that case you'll also need to ensure the properties have been removed. For example:

(let* ((str (propertize "foo \"bar\"" 'bar "baz")))
  (set-text-properties 0 (length str) nil str)
  (prin1-to-string str))
=> "\"foo \\\"bar\\\"\""
ebpa
  • 7,449
  • 29
  • 55