mediahub-fe/utils/globals.tsx

66 lines
1.7 KiB
TypeScript

import { format } from "date-fns";
import { id, tr } from "date-fns/locale";
export const generateLocalizedPath = (href: string, locale: string): string => {
if (href.startsWith(`/${locale}`)) {
return href;
}
return `/${locale}${href}`;
};
export function textEllipsis(
str: string,
maxLength: number,
{ side = "end", ellipsis = "..." } = {}
) {
if (str !== undefined && str?.length > maxLength) {
switch (side) {
case "start":
return ellipsis + str.slice(-(maxLength - ellipsis.length));
case "end":
default:
return str.slice(0, maxLength - ellipsis.length) + ellipsis;
}
}
return str;
}
export function formatDateToIndonesian(d: Date) {
try {
const dateString = format(d, "d MMMM yyyy HH:mm", { locale: id });
return dateString;
} catch (error) {
return "";
}
}
export function htmlToString(str: string) {
if (str == undefined || str == null) {
return "";
}
return (
str
.replaceAll(/<style[^>]*>.*<\/style>/gm, "")
// Remove script tags and content
.replaceAll(/<script[^>]*>.*<\/script>/gm, "")
// Replace &nbsp,&ndash
.replaceAll("&nbsp;", "")
.replaceAll("&ndash;", "-")
// Replace quotation mark
.replaceAll("&ldquo;", '"')
.replaceAll("&rdquo;", '"')
// Remove all opening, closing and orphan HTML tags
.replaceAll(/<[^>]+>/gm, "")
// Remove leading spaces and repeated CR/LF
.replaceAll(/([\n\r]+ +)+/gm, "")
);
}
export function getOnlyDate(date: Date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}