tailwind-nextjs-blog/lib/utils/htmlEscaper.ts

23 lines
556 B
TypeScript
Raw Normal View History

2022-07-17 21:40:41 +08:00
const { replace } = ''
// escape
const ca = /[&<>'"]/g
const esca = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;',
}
const pe = (m: keyof typeof esca) => esca[m]
2022-07-17 21:40:41 +08:00
/**
* 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)