b0nes
Version:
Zero-dependency component library and SSR/SSG framework
20 lines (19 loc) • 596 B
JavaScript
/**
* Escapes HTML special characters to prevent XSS attacks
* @param {string} unsafe - The string to escape
* @returns {string} The escaped string safe for HTML insertion
* @example
* escapeHtml('<script>alert("xss")</script>')
* // Returns: '<script>alert("xss")</script>'
*/
export const escapeHtml = (unsafe) => {
if (typeof unsafe !== 'string') {
return '';
}
return unsafe
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};