JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1332
  • Score
    100M100P100Q114628F
  • License ISC

Truncates the text at the last space before the given length.

Package Exports

  • truncate-text-between-words
  • truncate-text-between-words/lib/index.cjs
  • truncate-text-between-words/lib/index.mjs

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (truncate-text-between-words) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Truncates the text at the last space found before the given length. Adds "..." to indicate that the text is truncated.

CI npm Ko-fi

Usage

import {
    truncateText,
    getPositionOfLastSpaceBeforeIndex,
} from 'truncate-text-between-words';

Let's use this text as example:

// Lenght:        5    10   15   20   25
//                ↓    ↓    ↓    ↓    ↓
const TEXT = 'Lorem ipsum dolor sit amet.';

truncateText

Parameters:

type TruncateTextOptions = {
    hideIfNoWords?: boolean;
    dotsInsteadOfEllipsis?: boolean;
};

truncateText(text: string, maxLength: number, options?: TruncateTextOptions);

Options

hideIfNoWords - default: false - Hide the ellipsis if there are no words to show

truncateText(TEXT, 3);
// Output: ...

truncateText(TEXT, 3, { hideIfNoWords: true });
// Output:

dotsInsteadOfEllipsis - default: false - Use three dots instead of the ellipsis unicode character U+2026

Other examples

truncateText(TEXT, 6);
// Output: Lorem...

truncateText(TEXT, 15);
// Output: Lorem ipsum...

truncateText(TEXT, 50);
// Output: Lorem ipsum dolor sit amet.

getPositionOfLastSpaceBeforeIndex

getPositionOfLastSpaceBeforeIndex(text: string, index: number);
getPositionOfLastSpaceBeforeIndex(TEXT, 3);
// Output: -1

getPositionOfLastSpaceBeforeIndex(TEXT, 6);
// Output: 5

getPositionOfLastSpaceBeforeIndex(TEXT, 15);
// Output: 11

getPositionOfLastSpaceBeforeIndex(TEXT, 50);
// Output: 21