Simple way to un-escape escaped unpritable encoded string returned by mvc application

与世无争的帅哥 提交于 2019-12-02 06:59:34
Arghya C

From the links in the comments, I got a working solution, thanks to this post. In short, this worked for now.

var unescapedString = System.Text.RegularExpressions.Regex.Unescape(escapedString);

Longer version : Little more details for those who might face similar issues.

This is a typical sample of the strings that I was trying to make sane (readable & printable)

"Something didn\u0027t work right while processing this request! \r\nSee detailed logs \u003e d:\Sandboxes\UGBNC\Stage\Logs\ArgLog2087129002.log"

(1) Though the string came from a web response, this was not HTML, rather a JSON. So, the HTML decode methods like new WebUtility.HtmlDecode(str) or older System.Web HttpUtility.HtmlDecode(str) did not work.

(2) Characters like \u0027 are unicode characters (this ones for apostrophe '), but trying with System.Text.Encoding.Unicode yielded no good result. (Maybe I missed the trick!)

(3) Basically what I needed was to convert characters like \u0027, \r\n, \\ to their printable format. For that the System.Text.RegularExpressions.Regex.Unescape() method worked fine on my strings. This method converts all the escaped characters in the string to their unescaped form.

Note: Anyone using this method, please refer the msdn doc first. This method has some limitations, it's not perfect and might give wrong result in some scenarios.

Check this & this for better solutions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!