I was analysing a piece of code(written by someone else) in AngularJS and came across the below block with some string operations with special characters. What do we mean by the following expressions? It would be great if someone can please throw some light on these:
str = str.replace(/&/g, "&");
str = str.replace(/</g, "<");
str = str.replace(/>/g, ">");
str = str.replace(/"/g, """);
str = str.replace(/'/g, "'");
where str
is a string
object
Thanks in advance
2
Answers
This is about escaping special characters for HTML.
And the way it writes regular expression is more likely JavaScript than C#.
It’s doing XML string escaping by hand instead of calling one of the many provided functions that do it for you and do it correctly and much, much more efficiently:
SecurityElement.Escape
(best by far, no dependencies)HttpUtility.HtmlEncode
(worse, lots of dependencies)XDocument
orXmlTextWriter