How can I escape single and double quotes in a string?
I want to escape single and double quotes together. I know how to pass them separately but don't know how to pass both of them.
e.g: str = "ruby 'on rails" " = ruby 'on rails"
The easiest way is to use escape_javascript http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html it "Escapes carriage returns and single and double quotes for JavaScript segments."
No escaping is used with single quotes. Use a double backslash as the escape character for backslash.
You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.
Double Quotes inside verbatim strings can be escaped by using 2 sequential double quotes "" to represent one double quote " in the resulting string. var str = @"""I don't think so,"" he said.
My preferred way is to not worry about escaping and instead use %q
, which behaves like a single-quote string (no interpolation or character escaping), or %Q
for double quoted string behavior:
str = %q[ruby 'on rails" ] # like single-quoting str2 = %Q[quoting with #{str}] # like double-quoting: will insert variable
See https://docs.ruby-lang.org/en/trunk/syntax/literals_rdoc.html#label-Strings and search for % strings
.
Use backslash to escape characters
str = "ruby \'on rails\" "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With