How to Sanitize User Input in JavaScript: Simple and Safe Methods
string.replace() to escape special characters like <, >, and &. Additionally, validate input by checking its type and length to ensure it meets expected rules before using it.Syntax
Sanitizing user input usually involves replacing special characters with safe equivalents to prevent code injection. The common method is using string.replace() with regular expressions.
Example syntax:
input.replace(/&/g, '&')replaces all&with&input.replace(/</g, '<')replaces all<with<input.replace(/>/g, '>')replaces all>with>
function sanitizeInput(input) { return input .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); }
Example
This example shows how to sanitize a user input string by escaping special HTML characters to prevent malicious code from running in a webpage.
function sanitizeInput(input) { return input .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } const userInput = '<script>alert("Hi")</script>'; const safeInput = sanitizeInput(userInput); console.log('Sanitized input:', safeInput);
Common Pitfalls
One common mistake is trusting user input without sanitizing, which can lead to security issues like Cross-Site Scripting (XSS). Another is only sanitizing some characters but missing others, leaving vulnerabilities.
Also, sanitizing input is not the same as validating it. Validation checks if input meets rules (like length or format), while sanitizing cleans harmful characters.
/* Wrong: Using input directly in HTML */ const userInput = '<img src=x onerror=alert(1)>'; document.body.innerHTML = userInput; // Dangerous! /* Right: Sanitize before use */ function sanitizeInput(input) { return input .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } const safeInput = sanitizeInput(userInput); document.body.innerHTML = safeInput; // Safe display
Quick Reference
Tips for sanitizing user input in JavaScript:
- Escape special HTML characters:
&,<,>,",' - Use
string.replace()with global regex to replace all occurrences - Validate input length and format before processing
- Never trust user input directly in HTML or scripts
- Consider libraries like DOMPurify for complex sanitization needs