Rendering HTML
Servers often build HTML from data. Escape every value you insert, otherwise users can inject scripts.
Example
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const render = (items) => `<ul>${items.map((i) => `<li>${esc(i)}</li>`).join('')}</ul>`;
console.log(render(['A & B', '<script>alert(1)</script>']));Result
<ul><li>A & B</li><li><script>alert(1)</script></li></ul>
Exercise
Name the attack.
injectionQuiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.