How to encode special characters in HTML (encode, not entitize) but exclude HTML tags

460 Views Asked by At

So I'm trying to encode html special characters (like ®, &, ©) I find on the front-end, but I can't figure out how to avoid also encoding HTML tags (like <br>, or <i>).

This is what I've tried so far:

var encodedHtml = HttpUtility.HtmlEncode("Encode this: ®, &, © but not this: <b>")

Console.WriteLine(encodedHtml);

The result is: Encode this: &#174;, &amp;, &#169; but not this: &lt;b&gt;

The result I want is this: Encode this: &#174;, &amp;, &#169; but not this: <b>

I've also tried this, based on this post:

var entitizedHtml = HtmlEntity.Entitize("Encode this:®, &, © but not this: <b>"); Console.WriteLine(entitizedHtml );

The result is:Encode this: &reg;, &, &reg; but not this: <b>

The entitized result is close to what I want, but I'm trying to see if I can convert the the HTML special characters to their HTML code versions rather than their HTML entity versions.

Anyone have any suggestions? I'm thinking I might have to figure out how to parse through the string to check for HTML tags, but I'm not too sure what the best way to do that is.

0

There are 0 best solutions below