skip to Main Content

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, "&lt;");
str = str.replace(/>/g, "&gt;");
str = str.replace(/"/g, "&quot;");
str = str.replace(/'/g, "&apos;");

where str is a string object
Thanks in advance

2

Answers


  1. This is about escaping special characters for HTML.
    And the way it writes regular expression is more likely JavaScript than C#.

    Login or Signup to reply.
  2. 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)
    • And of course, all the xml writers like XDocument or XmlTextWriter
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search