portal / frontend /src /utils.js
ChandimaPrabath's picture
Update UI #New Theme
56b61e0
// utils.js
import axios from 'axios';
/**
* Fetches the country name from a given country code.
* @param {string} code - The country code (e.g., 'ind', 'usa').
* @returns {Promise<string>} - The country name.
*/
export const getCountryName = async (code) => {
try {
const response = await axios.get(`https://restcountries.com/v3.1/alpha/${code}`);
let name = response.data[0]?.name?.common || "Unknown Country";
console.log(name);
return name
} catch (error) {
console.error("Failed to fetch country name:", error);
return "Unknown Country";
}
};
/**
* Formats a date string into a more readable format.
* @param {string} dateStr - The date string (e.g., '2023-08-04').
* @returns {string} - The formatted date.
*/
export const formatDate = (dateStr) => {
const options = { year: 'numeric', month: 'long', day: 'numeric' };
return new Date(dateStr).toLocaleDateString(undefined, options);
};
/**
* Capitalizes the first letter of a string.
* @param {string} str - The string to capitalize.
* @returns {string} - The capitalized string.
*/
export const capitalizeFirstLetter = (str) => {
if (!str) return '';
return str.charAt(0).toUpperCase() + str.slice(1);
};
/**
* Checks if a value is a valid email address.
* @param {string} email - The email address to validate.
* @returns {boolean} - True if valid, false otherwise.
*/
export const isValidEmail = (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
/**
* Converts a string to a URL-friendly slug.
* @param {string} text - The text to convert.
* @returns {string} - The slugified text.
*/
export const slugify = (text) => {
return text
.toString()
.toLowerCase()
.trim()
.replace(/[\s\W-]+/g, '-');
};