Senior
What symbols need to be escaped to protect against XSS attacks?
sobes.tech AI
Answer from AI
To protect against XSS attacks, it is necessary to escape special characters that can be interpreted by the browser as HTML or JavaScript. The main characters to escape:
&(ampersand) →&<(less than) →<>(greater than) →>"(double quote) →"'(single quote) →'
Escaping these characters prevents malicious code injection into HTML or attributes.
Example in JavaScript:
function escapeHTML(str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
const userInput = '<script>alert("XSS")</script>';
const safeString = escapeHTML(userInput);
console.log(safeString); // <script>alert("XSS")</script>
It is also important to use Content Security Policy (CSP) and avoid inserting unchecked HTML.