Data formatting utility functions in JavaScript are functions that are used to manipulate and format data in a specific way. These functions can be used to format dates, numbers, and strings according to a particular format or to perform other data formatting operations.
date-time.ts
Copy export const formatDate = (dateString: string): string => {
const date = new Date(dateString);
const options: Intl.DateTimeFormatOptions = {
year: "numeric",
month: "long",
day: "numeric",
};
return date.toLocaleDateString("en-US", options);
};
export const formatTime = (timeString: string): string => {
const time = new Date(`1970-01-01T${timeString}`);
const options: Intl.DateTimeFormatOptions = {
hour: "numeric",
minute: "numeric",
hour12: true,
};
return time.toLocaleTimeString("en-US", options);
};
export const formatDateTime = (dateTimeString: string): string => {
const date = new Date(dateTimeString);
const options: Intl.DateTimeFormatOptions = {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true,
};
return date.toLocaleDateString("en-US", options);
};
number.ts
Copy export const formatNumber = (
num: number,
decimalPlaces: number = 0
): string => {
return num.toFixed(decimalPlaces).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
export const formatCurrency = (
num: number,
currencySymbol: string = "$"
): string => {
return `${currencySymbol}${formatNumber(num, 2)}`;
};
url.ts
Copy export const formatUrl = (url: string): string => {
const parsedUrl = new URL(url);
let formattedUrl = parsedUrl.protocol;
formattedUrl += parsedUrl.host;
formattedUrl += parsedUrl.pathname.replace(/\/$/, "");
formattedUrl += parsedUrl.search;
return formattedUrl;
};