sanitize

Benchmark created on


Setup

function makeid(length) {
	let result = '';
	const characters = '<<<<>>>>\'""""====ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	const charactersLength = characters.length;
	let counter = 0;
	while (counter < length) {
		result += characters.charAt(Math.floor(Math.random() * charactersLength));
		counter += 1;
	}
	return result;
}

const str = makeid(10);

const sanitizeSymbols = {
	'&': '&amp;',
	'<': '&lt;',
	'>': '&gt;',
	'"': '&quot;',
	"'": '&#x27;',
	'`': '&#x60;',
	'=': '&#x3D;',
};

function sanitizeHtmlPlaintextRegex(text) {
	return text.replaceAll(/[&<>"'`=]/g, (match) => {
		return sanitizeSymbols[match];
	});
}

function sanitizeHtmlPlaintextReplaceAlls(text) {
	return text
		.replaceAll('&', '&amp;')
		.replaceAll('<', '&lt;')
		.replaceAll('>', '&gt;')
		.replaceAll('"', '&quot;')
		.replaceAll("'", '&#x27;')
		.replaceAll('`', '&#x60;')
		.replaceAll('=', '&#x3D;');
}

function sanitizeHtmlPlaintextReduce(text) {
	const symbols = [
		{ symbol: '&', sub: '&amp;' },
		{ symbol: '<', sub: '&lt;' },
		{ symbol: '>', sub: '&gt;' },
		{ symbol: '"', sub: '&quot;' },
		{ symbol: "'", sub: '&#x27;' },
		{ symbol: '`', sub: '&#x60;' },
		{ symbol: '=', sub: '&#x3D;' },
	];
	return symbols.reduce((prev, { symbol, sub }) => {
		return prev.replaceAll(symbol, sub);
	}, text);
}

Test runner

Ready to run.

Testing in
TestOps/sec
regex
sanitizeHtmlPlaintextRegex(str);
ready
replaceAlls
sanitizeHtmlPlaintextReplaceAlls(str);
ready
reduce
sanitizeHtmlPlaintextReduce(str);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.