I am consuming an api and I noticed that it comes back with "'s"
and not an apostrophe. Since I am not going to be displaying this text in html this will make my text look weird when I display to the user.
How can I remove or convert(preferred)? I don't know if this api I am working with will be sending any more of these special codes so I don't know if I can just simply do a replace.
As of .NET 4.0 you can use System.Web.HttpUtility.HtmlDecode
(resides in the System.Web.dll
assembly, in the namespace System.Web
).
Or you could use the System.Net.WebUtility.HtmlDecode
function, you don't even need an extra reference for this (because it resides in the System.dll
assembly, in the namespace System.Net
).
Usage:
string myStringToDecode = "Hello 'World'";
string decodedString = System.Web.HttpUtility.HtmlDecode(myStringToDecode);
// or
string decodedString = System.Net.WebUtility.HtmlDecode(myStringToDecode);
The MatchEveluator is available since .NET 1.0 and comes in handy if you want to address this problem in a more generic fashion - i.e. do more than just HTML character decoding. The general recipe looks like this:
MatchEvaluator ev = (Match m) => Char.ToString((char)Int32.Parse(m.Groups[1].Value));
string result = Regex.Replace("The king's key.";, @"&#(\d+);", ev);
Why aren't you uysing String.Replace Method (String, String) for this purpose. Just find your string and replace it with your required one.
string myStringToDecode = "Hello 'World'";
myStringToDecode.Replace("'","'");