Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a single quote into an escaped single quote within a string

It pains me to ask this, but, for some reason I have not been able to get this to work (it's late in the day, yes, that's my excuse).

Let's say I have this string:

s = "John's book." 

Using the replace method from the object String, I want to turn it into this:

s = "John\'s book." 

I would have expected this code to give me what I want:

s = s.Replace("'", "\\'") 

But, that results in:

"John\\'s book." 
like image 821
Justin Helgerson Avatar asked May 23 '12 22:05

Justin Helgerson


People also ask

How do you escape quotes within a quote?

It's done by finishing an already-opened one ( ' ), placing the escaped one ( \' ), and then opening another one ( ' ). It's done by finishing already opened one ( ' ), placing a quote in another quote ( "'" ), and then opening another one ( ' ).

How do you pass a single quote in a string?

Enclosing Quotation Marks That means strings containing single quotes need to use double quotes and strings containing double quotes need to use single quotes. "It's six o'clock."; 'Remember to say "please" and "thank you."'; Alternatively, you can use a backslash \ to escape the quotation marks.

How do you escape a quote from a string?

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.

How do I escape a single quote in Linux?

A single quote is not used where there is already a quoted string. So you can overcome this issue by using a backslash following the single quote. Here the backslash and a quote are used in the “don't” word. The whole string is accompanied by the '$' sign at the start of the declaration of the variable.


1 Answers

Do this so you don't have to think about it:

s = s.Replace("'", @"\'"); 
like image 55
BeemerGuy Avatar answered Oct 11 '22 20:10

BeemerGuy