Essential Helper Functions for Your JavaScript Projects
Ayantunji Timilehin
Posted on May 31, 2024
When working on various JavaScript projects, I often find myself needing some handy helper functions to simplify repetitive tasks. Below are some of the helper functions that have proven to be very useful in my projects. These functions cover a range of tasks from string manipulation to number checks and date formatting.
1. Capitalize the First Letter of a String
This function takes a string and capitalizes the first letter while converting the rest of the string to lowercase. This is particularly useful for formatting names or titles.
export const capitalizeFirstLetter = (word?: string) => {
return word ? word.charAt(0).toUpperCase() + word.toLocaleLowerCase().slice(1) : '';
};
2. Format an Array to a Sentence
When you have an array of strings that you need to format as a sentence, this function joins the array elements with commas and replaces the last comma with "and".
export const formatArrayToSentence = (stringArr: string[]) => {
if (!stringArr?.length) return '';
return stringArr.join(', ').replace(/, ([^,]*)$/, ' and $1.');
};
3. Format Date
This function uses the moment library to format dates. It can format a date to DD/MM/YYYY or to a time format HH:mm A based on the isTime flag.
import moment from 'moment';
export const formatDate = (date: string, isTime = false) => {
if (!date) return '';
const parsedDate = moment(date);
if (isTime) return parsedDate.format('HH:mm A');
return parsedDate.format('DD/MM/YYYY');
};
4. Truncate Text
To shorten a text string to a specified length and append an ellipsis (...), use this function. It ensures the text does not exceed the desired length.
export const truncateText = (text: string, maxLength: number) => {
if (text.length <= maxLength) return text;
return text.substring(0, maxLength) + '...';
};
5. Check for Uppercase, Lowercase, Numbers, and Special Characters
These functions use regular expressions to check if a string contains at least one uppercase letter, one lowercase letter, one number, or one special character. These are particularly useful for password validation.
export const containsAtleastOneUpperCase = (val: string) => /(?=.*?[A-Z])/.test(val);
export const containsAtleastOneLowerCase = (val: string) => val ? /(?=.*?[a-z])/.test(val) : false;
export const containsAtleastOneNumber = (val: string) => /(?=.*[0-9])/.test(val);
export const containsAtLeastOneSpecialChar = (val: string) => /(?=.*[$&+,:;=?@#|'<>.^*_()%!-])/.test(val);
6. Check if a Number is Even or Odd
These simple functions check if a number is even or odd.
export const isEven = (number: number) => (number ? number % 2 === 0 : false);
export const isOdd = (number: number) => number % 2 !== 0;
7. Check for Non-Empty Object
This function checks if an object is not empty, which is useful for validating that an object has properties before performing operations on it.
export const isNonEmptyObject = (obj: Record<string, unknown>) => {
return typeof obj === 'object' && obj !== null && Object.keys(obj).length > 0;
};
Conclusion
These helper functions are designed to make common tasks easier and your code more readable. By incorporating them into your projects, you can save time and ensure consistency across your codebase. Whether it's formatting strings, validating inputs, or checking object properties, these utilities cover a broad range of use cases that are essential in everyday JavaScript development.
Posted on May 31, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.