https://github.com/danielvigaru/truncate-text-between-words
https://github.com/danielvigaru/truncate-text-between-words
npm truncate-text
Last synced: 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/danielvigaru/truncate-text-between-words
- Owner: danielvigaru
- License: isc
- Created: 2022-07-10T09:26:01.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2025-02-05T20:04:29.000Z (5 months ago)
- Last Synced: 2025-04-10T16:55:01.563Z (3 months ago)
- Topics: npm, truncate-text
- Language: TypeScript
- Homepage: https://npmjs.com/package/truncate-text-between-words
- Size: 355 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
Truncates the text at the last space found before the given length. Adds "..." to indicate that the text is truncated.
[](https://github.com/danielvigaru/truncate-text-between-words/actions/workflows/node.js.yml)
[](https://www.npmjs.com/package/truncate-text-between-words)
[](https://ko-fi.com/Y8Y1DZBZU)## Usage
```javascript
import {
truncateText,
getPositionOfLastSpaceBeforeIndex,
} from 'truncate-text-between-words';
```### Let's use this text as example:
```javascript
// Lenght: 5 10 15 20 25
// ↓ ↓ ↓ ↓ ↓
const TEXT = 'Lorem ipsum dolor sit amet.';
```## truncateText
Parameters:
```typescript
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
```javascript
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
```javascript
truncateText(TEXT, 6);
// Output: Lorem...truncateText(TEXT, 15);
// Output: Lorem ipsum...truncateText(TEXT, 50);
// Output: Lorem ipsum dolor sit amet.
```## getPositionOfLastSpaceBeforeIndex
```typescript
getPositionOfLastSpaceBeforeIndex(text: string, index: number);```
```javascript
getPositionOfLastSpaceBeforeIndex(TEXT, 3);
// Output: -1getPositionOfLastSpaceBeforeIndex(TEXT, 6);
// Output: 5getPositionOfLastSpaceBeforeIndex(TEXT, 15);
// Output: 11getPositionOfLastSpaceBeforeIndex(TEXT, 50);
// Output: 21
```