Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Special characters into Html Encoded characters

I want to converter all special characters into Html encoded characters. I found many post related to used HttpUtility.HtmlEncode(); , but it's only convert some of special characters like "&", "<", ">".

Is there any way to convert all special character like "š","Ø","þ","›","Ù" into Html entity using C# or javascript?

like image 544
Ishan Jain Avatar asked Jun 14 '13 10:06

Ishan Jain


People also ask

How do you convert special characters such as and spaces to their respective HTML or URL encoded equivalents?

replace(/&/g, "&amp;"). replace(/>/g, "&gt;"). replace(/</g, "&lt;"). replace(/"/g, "&quot;");

What is an HTML encoded string?

HTML encoding ensures that text will be correctly displayed in the browser, not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as an opening or closing bracket of an HTML tag.


2 Answers

The Microsoft AntiXss Library can accomplish this;

string p = Microsoft.Security.Application.Encoder.HtmlEncode("aaa <b>sdf</b> š,Ø,þ,›,Ù", true);
Response.Write(p);

For

aaa &lt;b&gt;sdf&lt;/b&gt; &scaron;,&Oslash;,&thorn;,&rsaquo;,&Ugrave;
like image 77
Alex K. Avatar answered Nov 02 '22 23:11

Alex K.


you can also do as follows without AntiXSS

public static string HtmlEncode (string text)
{
    string result;
    using (StringWriter sw = new StringWriter())
    {
        var x = new HtmlTextWriter(sw);
        x.WriteEncodedText(text);
        result = sw.ToString();
    }
    return result;

}
like image 26
Shahyad Sharghi Avatar answered Nov 03 '22 00:11

Shahyad Sharghi