stringzy
Version:
A versatile string manipulation library providing a range of text utilities for JavaScript and Node.js applications.
37 lines (36 loc) • 1.03 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.escapeHtml = escapeHtml;
/**
* Escapes special HTML characters in a string to their corresponding HTML entities.
*
* This function replaces the following characters:
* - `&` with `&`
* - `<` with `<`
* - `>` with `>`
* - `"` with `"`
* - `'` with `'`
*
* This is useful to prevent HTML injection or XSS attacks when inserting user input into HTML.
*
* @param {string} str - The string to escape.
* @returns {string} The escaped string with HTML entities.
*
* @example
* escapeHtml('<div class="test">Hello & Welcome</div>');
* // "<div class="test">Hello & Welcome</div>"
*
* @example
* escapeHtml("It's a test!");
* // "It's a test!"
*/
function escapeHtml(str) {
const htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
};
return str.replace(/[&<>"']/g, (match) => htmlEscapes[match]);
}
;