🤯 60% OFF BLACK FRIDAY SALE 650+ books, courses & coding assessments!

jQuery Strip Harmful Characters from String

Sam Deering
Share

jQuery Function to strip out all potentially harmful characters from an input field. Useful for extra security measures of filtering requests to your server before using AJAX for example.

Also see: 10 jQuery Security Plugins

/**
 * Strip out all potentially harmful characters from an input field
 * @param {String} str
 * @returns {String}
 */
filterInputText = function(str)
{
	try
	{
		return str.replace(/s+/gm, ' ').match(/[a-zA-Z0-9(), .!/:%@&?+_=-$]+/gm).join('');
	}
	catch(e)
	{
		return '';
	}
}