0

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 Apr 11 '17 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 Apr 11 '17 at 7:03
3

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

Personally, I'd stick with format.

(format "\"%s\"" "foo")
=> "\"foo\""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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