sanitize (v3)

Revision 3 of this 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(25);

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

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

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

const symbols = [
		{ symbol: '&', sub: '&amp;' },
		{ symbol: '<', sub: '&lt;' },
		{ symbol: '>', sub: '&gt;' },
		{ symbol: '"', sub: '&quot;' },
		{ symbol: "'", sub: '&#x27;' },
		{ symbol: '`', sub: '&#x60;' },
		{ symbol: '=', sub: '&#x3D;' },
	];
const sanitizeHtmlPlaintextReduce = (text) =>
	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.