Skip to main content Accessibility Feedback

encodeHTML.js

Encode the HTML in a user-submitted string to reduce the risk of XSS attacks.

Note: This converts all HTML in a string to plain text. If you want to allow users to include markup, use cleanHTML() instead.

Source Code

Example

let app = document.querySelector('#app');
app.innerHTML = encodeHTML('<img src="x" onerror="alert(1)">');

The helper function

/**
 * Encode the 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
 */
function encodeHTML (str) {
	return str.replace(/data:/gi, '').replace(/javascript:/gi, '').replace(/[^\w-_. ]/gi, function (c) {
		return `&#${c.charCodeAt(0)};`;
	});
}