DEV Community

Utku Yılmaz
Utku Yılmaz

Posted on

Essential Helper Functions for Your JavaScript Projects

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) : '';
};
Enter fullscreen mode Exit fullscreen mode

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.');
};
Enter fullscreen mode Exit fullscreen mode

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');
};
Enter fullscreen mode Exit fullscreen mode

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) + '...';
};

Enter fullscreen mode Exit fullscreen mode

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);


Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Your examples are all written in TypeScript? 🤔

Interestingly, number 2 is built into JS and can even cope with other languages:

const vehicles = ['Motorcycle', 'Bus', 'Car']

// English
const formatter = new Intl.ListFormat('en')
console.log(formatter.format(vehicles))  // "Motorcycle, Bus, and Car"
// German
const formatter2 = new Intl.ListFormat('de')
console.log(formatter2.format(vehicles))  // "Motorcycle, Bus und Car"
Enter fullscreen mode Exit fullscreen mode