Utilities
truncate

truncate

Truncates a string to a maximum length and adds a suffix if it was truncated.

Installation

npm install @madeinhaus/utils

Import

import { truncate } from '@madeinhaus/utils';

Parameters

  • str (string): The string to truncate.
  • maxLength (number): The maximum length of the truncated string.
  • suffix (string, optional): The suffix to add to the truncated string. Defaults to "...".

Returns

  • (string): The truncated string.

Usage

import { truncate } from '@madeinhaus/utils';
 
const str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
const maxLength = 20;
const suffix = '...';
const truncatedStr = truncate(str, maxLength, suffix); // 'Lorem ipsum dolor si...'

In this example, we import the truncate function from the @madeinhaus/utils package and use it to truncate a string to a maximum length and add a suffix if it was truncated.