es-toolkit
Version:
A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.
27 lines (26 loc) • 776 B
JavaScript
//#region src/string/escape.ts
const htmlEscapes = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'"
};
/**
* Converts the characters "&", "<", ">", '"', and "'" in `str` to their corresponding HTML entities.
* For example, "<" becomes "<".
*
* @param str The string to escape.
* @returns Returns the escaped string.
*
* @example
* escape('This is a <div> element.'); // returns 'This is a <div> element.'
* escape('This is a "quote"'); // returns 'This is a "quote"'
* escape("This is a 'quote'"); // returns 'This is a 'quote''
* escape('This is a & symbol'); // returns 'This is a & symbol'
*/
function escape(str) {
return str.replace(/[&<>"']/g, (match) => htmlEscapes[match]);
}
//#endregion
export { escape };