Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to HTML safe string

Tags:

I am creating a some dynamically generated HTML

bldr.AppendLine("<a>"); string userText = user.Company; bldr.AppendLine(userText); bldr.AppendLine("</a>"); 

How can I ensure that whatever the company's name is, will appear as it should, but also if they try to inject any HTML in thier name it will simply appear in plain text.

For instance if they tried to use the name "<script>alert("Do Bad!")</script>" that's exactly what will appear on the page, in plain text.

But I also want to avoid "A & C" translating to "A \u0026 C", which is what happens when I use

HttpUtility.JavaScriptStringEncode(user.Company); 
like image 592
TruthOf42 Avatar asked May 21 '14 12:05

TruthOf42


People also ask

How to convert string to HTML tag?

The parseFromString() method of the DOMParser interface converts a string which contains HTML and returns as an HTMLDocument. OUTPUT: You can see that the HTML string is converted to an HTML element as a DOM node. Now, you can use the methods of DOM nodes like appendChild() to use the result.

How to convert string to HTML code in c#?

You can use the same class HttpUtility you have use to javascript, but, for html , for sample: bldr. AppendFormat("<a>{0}</a>\n", HttpUtility. HtmlEncode(user.


2 Answers

You can use the same class HttpUtility you have use to javascript, but, for html, for sample:

bldr.AppendFormat("<a>{0}</a>\n", HttpUtility.HtmlEncode(user.Company)); 

There is also the inverse way using HttpUtility.HtmlDecode(string).

like image 93
Felipe Oriani Avatar answered Oct 12 '22 11:10

Felipe Oriani


An alternative without a dependency to System.Web:

System.Net.WebUtility.HtmlEncode() 
like image 23
MarkO Avatar answered Oct 12 '22 09:10

MarkO