Skip to main content Accessibility Feedback

sanitizeHTML.js

Sanitize and encode all HTML in a user-submitted string to prevent XSS attacks.

This removes all markup from a string. If you want to allow users to include markup, use a tool like DOMPurify instead.

/**
 * Sanitize and encode all HTML in a user-submitted string
 * https://portswigger.net/web-security/cross-site-scripting/preventing
 * @param  {String} str  The user-submitted string
 * @return {String} str  The sanitized string
 */
var sanitizeHTML = function (str) {
	return str.replace(/[^\w. ]/gi, function (c) {
		return '&#' + c.charCodeAt(0) + ';';
	});
};