0
0
JavascriptHow-ToBeginner · 4 min read

How to Sanitize User Input in JavaScript: Simple and Safe Methods

To sanitize user input in JavaScript, use 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 &amp;
  • input.replace(/</g, '&lt;') replaces all < with &lt;
  • input.replace(/>/g, '&gt;') replaces all > with &gt;
javascript
function sanitizeInput(input) {
  return input
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
💻

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.

javascript
function sanitizeInput(input) {
  return input
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

const userInput = '<script>alert("Hi")</script>';
const safeInput = sanitizeInput(userInput);
console.log('Sanitized input:', safeInput);
Output
Sanitized input: &lt;script&gt;alert(&quot;Hi&quot;)&lt;/script&gt;
⚠️

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.

javascript
/* 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, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
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

Key Takeaways

Always escape special HTML characters in user input to prevent XSS attacks.
Use string replacement with regular expressions to sanitize input safely.
Validate input format and length separately from sanitization.
Never insert raw user input directly into HTML or scripts.
For complex cases, use trusted libraries like DOMPurify.