Fix the HTML escaper for user comments

Review the AI's codeEasy10 min

Your task

A comment component turned newlines into <br/> and passed the raw body to dangerouslySetInnerHTML, so a comment holding <img src=x onerror=...> ran script for every reader. The fix escapes the body first, and other templates will use the same helper inside attribute values.

An assistant wrote escape_comment_html(body). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • body: the comment exactly as the user typed it. It can be empty and can hold any character.
  • Return the HTML string to render.

Rules the tests check:

  • Go through the body one character at a time, left to right, and replace these characters:
    • & becomes &amp;
    • < becomes &lt;
    • > becomes &gt;
    • " becomes &quot;
    • ' becomes &#39;
    • a newline, \n, becomes <br/>
  • Every other character stays as it is, including \r and tabs.
  • Each input character is replaced once, and what you write is never scanned again. So &lt; typed by the user becomes &amp;lt;, and the <br/> you write stays markup.
  • An empty body returns an empty string.

Examples

escape_comment_html(body: str) -> str
Example 1
Inputescape_comment_html("hello world")
Output"hello world"
Example 2
Inputescape_comment_html("line one\nline two")
Output"line one<br/>line two"
Example 3
Inputescape_comment_html("<img src=x onerror=alert(1)>")
Output"&lt;img src=x onerror=alert(1)&gt;"