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.

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

1 Answer 1


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\\\"\""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.