Skip to content

CodeNot attempted

escapeHtml

Difficulty: easy

Write escapeHtml(text) so the result is safe to put inside HTML or a quoted attribute. Replace & < > " ' with &amp; &lt; &gt; &quot; &#39;. Make sure nothing gets escaped twice.

Show reference solution
const replacements: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
};
export function escapeHtml(text: string): string {
let result = '';
for (const char of text) {
// Swap the five special characters, keep everything else as it is.
result += replacements[char] ?? char;
}
return result;
}
Loading editor…