Home » c# » Strip double quotes from a string in .NET

Strip double quotes from a string in .NET

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’m trying to match on some inconsistently formatted HTML and need to strip out some double quotes.

Current:

<input type="hidden">

The Goal:

<input type=hidden>

This is wrong because I’m not escaping it properly:

s = s.Replace(“””,””);

This is wrong because there is not blank character character (to my knowledge):

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

What is syntax / escape character combination for replacing double quotes with an empty string?

Answers:

I think your first line would actually work but I think you need four quotation marks for a string containing a single one (in VB at least):

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

for C# you’d have to escape the quotation mark using a backslash:

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

Questions:
Answers:
s = s.Replace("\"", "");

You need to use the \ to escape the double quote character in a string.

Questions:
Answers:

You can use either of these:

s = s.Replace(@"""","");
s = s.Replace("\"","");

…but I do get curious as to why you would want to do that? I thought it was good practice to keep attribute values quoted?

Questions:
Answers:

I didn’t see my thoughts repeated already, so I will suggest that you look at string.Trim in the Microsoft documentation for C# you can add a character to be trimmed instead of simply trimming empty spaces:

string withQuotes = "\"hellow\"";
string withOutQotes = withQuotes.Trim('"');

should result in withOutQuotes being "hello" instead of ""hello""

Questions:
Answers:
s = s.Replace("\"",string.Empty);

Questions:
Answers:

You have to escape the double quote with a backslash.

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

Questions:
Answers:

c#: "\"", thus s.Replace("\"", "")

vb/vbs/vb.net: "" thus s.Replace("""", "")

Questions:
Answers:
s = s.Replace( """", "" )

Two quotes next to each other will function as the intended ” character when inside a string.

Questions:
Answers:

s = s.Replace(@””””, “”);

Questions:
Answers:

This worked for me

//Sentence has quotes
string nameSentence = "Take my name \"Wesley\" out of quotes";
//Get the index before the quotes`enter code here`
int begin = nameSentence.LastIndexOf("name") + "name".Length;
//Get the index after the quotes
int end = nameSentence.LastIndexOf("out");
//Get the part of the string with its quotes
string name = nameSentence.Substring(begin, end - begin);
//Remove its quotes
string newName = name.Replace("\"", "");
//Replace new name (without quotes) within original sentence
string updatedNameSentence = nameSentence.Replace(name, newName);

//Returns "Take my name Wesley out of quotes"
return updatedNameSentence;