tailwind-nextjs-blog/lib/utils/htmlEscaper.ts
2022-10-17 15:37:01 +00:00

23 lines
561 B
TypeScript

const { replace } = '';
// escape
const ca = /[&<>'"]/g;
const esca = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;',
};
const pe = (m: keyof typeof esca) => esca[m];
/**
* Safely escape HTML entities such as `&`, `<`, `>`, `"`, and `'`.
* @param {string} es the input to safely escape
* @returns {string} the escaped input, and it **throws** an error if
* the input type is unexpected, except for boolean and numbers,
* converted as string.
*/
export const escape = (es: string): string => replace.call(es, ca, pe);