String Manipulation

String manipulation utility functions in TypeScript are functions that are used to manipulate strings in various ways. Strings are a sequence of characters that are commonly used in web development for things like displaying text, storing user input, and formatting data.

case-conversion.ts
export const capitalize = (str: string): string => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

export const decapitalize = (str: string): string => {
  return str.charAt(0).toLowerCase() + str.slice(1);
};

export const toCamelCase = (str: string): string => {
  return str
    .replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) => {
      return index === 0 ? word.toLowerCase() : word.toUpperCase();
    })
    .replace(/\s+/g, "");
};

export const toSnakeCase = (str: string): string => {
  return str.replace(/\s+/g, "_").toLowerCase();
};

export const toKebabCase = (str: string): string => {
  return str.replace(/\s+/g, "-").toLowerCase();
};
padding.ts
export const padStart = (
  str: string,
  targetLength: number,
  padString: string = " "
): string => {
  return str.padStart(targetLength, padString);
};

export const padEnd = (
  str: string,
  targetLength: number,
  padString: string = " "
): string => {
  return str.padEnd(targetLength, padString);
};
truncation.ts
export const truncate = (str: string, maxLength: number): string => {
  if (str.length > maxLength) {
    return str.substring(0, maxLength) + "...";
  } else {
    return str;
  }
};

export const truncateWords = (str: string, maxWords: number): string => {
  const words = str.split(" ");
  if (words.length > maxWords) {
    return words.slice(0, maxWords).join(" ") + "...";
  } else {
    return str;
  }
};

Last updated