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

23 lines
561 B
TypeScript
Raw Normal View History

2022-10-17 23:37:01 +08:00
const { replace } = '';
2022-07-17 21:40:41 +08:00
// escape
2022-10-17 23:37:01 +08:00
const ca = /[&<>'"]/g;
2022-07-17 21:40:41 +08:00
const esca = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;',
2022-10-17 23:37:01 +08:00
};
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.
*/
2022-10-17 23:37:01 +08:00
export const escape = (es: string): string => replace.call(es, ca, pe);