Search code examples
c#asp.netstringspecial-charactersunescapestring

Replacing special characther in string with ampersand


I have a URL which basically looks like this:

https://example.com/us/cgi-bin/webscr?cmd=_express-checkout\u0026token=EC-2BF46053LU471230V

The URL is generated from a statement like following:

if ((int)response.StatusCode == 200 || (int)response.StatusCode == 201)
  {
      var res = await content.ReadAsStringAsync();
      var url = HttpUtility.HtmlDecode(JsonConvert.DeserializeObject<PayPalBlueReference>(res).paypalTransaction.paypalUrl);

      return Json(Regex.Unescape(url), JsonRequestBehavior.AllowGet);
  }

For some reason my URL contains the:

\u0026

Sign which I'm not able to get rid of even after using

Regex.Unescape()

Method... I have even tried using the

Replace("\u0026","&") 

but that didn't work either...

The URL should be formatted like this:

https://example.com/us/cgi-bin/webscr?cmd=_express-checkout&token=EC-2BF46053LU471230V

Can someone help me out ?

Edit: the returned JSON from server looks like this:

"https://example.com/us/cgi-bin/webscr?cmd=_express-checkout\u0026token=EC-2BF46053LU471230V"

Edit2: This is using rokkerboci's method:

   if ((int)response.StatusCode == 200 || (int)response.StatusCode == 201)
        {
            var res = await content.ReadAsStringAsync();
            var url = HttpUtility.HtmlDecode(JsonConvert.DeserializeObject<PayPalBlueReference>(res).paypalTransaction.paypalUrl);

            return Json(url.Replace("\\u0026", "&"), JsonRequestBehavior.AllowGet);
        }

The response still contains \u0026


Solution

  • You can do it using the System.Web namespace:

    string encoded = "https://example.com/us/cgi-bin/webscr?cmd=_express-checkout\u0026token=EC-2BF46053LU471230V";
    
    var unencoded = HttpUtility.HtmlDecode(encoded);
    
    Console.WriteLine(unencoded);