Back to Home
Strings

How to Sanitize User Input

Escape HTML and remove dangerous characters

Quick Answer (2024 ES6+ Way)

javascript
function escapeHTML(str) {
  const div = document.createElement('div');
  div.textContent = str;
  return div.innerHTML;
}

const safe = escapeHTML('<script>alert("xss")</script>');
console.log(safe); // "&lt;script&gt;alert("xss")&lt;/script&gt;"

Live Example

javascript
// Escape HTML entities
function escapeHTML(str) {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  };
  return str.replace(/[&<>"']/g, m => map[m]);
}

console.log(escapeHTML('<div>Hello</div>'));

// Remove all HTML tags
function stripHTML(str) {
  return str.replace(/<[^>]*>/g, '');
}

console.log(stripHTML('<p>Text <b>bold</b></p>'));

// Sanitize filename
function sanitizeFilename(name) {
  return name
    .replace(/[^a-z0-9.-]/gi, '_')
    .replace(/_{2,}/g, '_')
    .toLowerCase();
}

console.log(sanitizeFilename('My File Name!.txt'));

// Remove SQL injection chars
function sanitizeSQL(str) {
  return str.replace(/['";\]/g, '');
}

Common Variations

Allow Safe HTML
javascript
function sanitizeHTML(str, allowedTags = ['b', 'i', 'em']) {
  return str.replace(/<(\/?)([^>]+)>/g, (match, slash, tag) => {
    const tagName = tag.split(' ')[0].toLowerCase();
    return allowedTags.includes(tagName) ? match : '';
  });
}
Validate Input
javascript
const isValidEmail = str => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
const isValidURL = str => {
  try {
    new URL(str);
    return true;
  } catch {
    return false;
  }
};

❌ Don't Do This (Outdated Way)

Never trust user input without sanitization

javascript
// DON'T DO THIS
element.innerHTML = userInput; // XSS vulnerability!

Browser Support

Works in all modern browsers (ES5+)

#strings#sanitize#security