Fix the HTML escaper for user comments
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&<becomes<>becomes>"becomes"'becomes'- a newline,
\n, becomes<br/>
- Every other character stays as it is, including
\rand tabs. - Each input character is replaced once, and what you write is never scanned again. So
<typed by the user becomes&lt;, and the<br/>you write stays markup. - An empty body returns an empty string.
Examples
escape_comment_html(body: str) -> strExample 1
Input
escape_comment_html("hello world")Output
"hello world"Example 2
Input
escape_comment_html("line one\nline two")Output
"line one<br/>line two"Example 3
Input
escape_comment_html("<img src=x onerror=alert(1)>")Output
"<img src=x onerror=alert(1)>"