Manipulation

import {
  capitalize, capitalizeWords, reverse, truncate,
  truncateWords, trim, insert, mask,
} from '@ppabari/strio/str';

capitalize

capitalize(str: string, lowerRest?: boolean): string

Uppercase the first character. Pass lowerRest = true to also lowercase the remainder.

capitalize('hello');       // β†’ 'Hello'
capitalize('hELLO');       // β†’ 'HELLO'
capitalize('hELLO', true); // β†’ 'Hello'

capitalizeWords

capitalizeWords(str: string): string

Capitalize the first letter of every whitespace-separated word.

capitalizeWords('hello world'); // β†’ 'Hello World'

reverse

reverse(str: string): string

Reverse a string. Unicode-aware β€” surrogate pairs (emoji) stay intact.

reverse('abc');  // β†’ 'cba'
reverse('aπŸ˜€b'); // β†’ 'bπŸ˜€a'

truncate

truncate(str: string, length: number, suffix?: string): string

Truncate to at most length characters, appending suffix (default '…') when truncation occurs. The suffix counts toward length.

truncate('The quick brown fox', 9);       // β†’ 'The quic…'
truncate('The quick brown fox', 9, '...'); // β†’ 'The qu...'
truncate('short', 20);                      // β†’ 'short'

truncateWords

truncateWords(str: string, count: number, suffix?: string): string

Truncate to at most count words.

truncateWords('The quick brown fox', 2); // β†’ 'The quick…'

trim

trim(str: string, chars?: string): string

Trim whitespace, or every character in chars, from both ends.

trim('  hi  ');        // β†’ 'hi'
trim('__hi__', '_');   // β†’ 'hi'
trim('xyabcyx', 'xy'); // β†’ 'abc'

insert

insert(str: string, index: number, substring: string): string

Insert substring at index. Negative indexes count from the end; out-of-range indexes clamp.

insert('helloworld', 5, ' '); // β†’ 'hello world'
insert('ac', 1, 'b');         // β†’ 'abc'

mask

mask(str: string, options?: {
  maskChar?: string;      // default '*'
  visibleStart?: number;  // default 0
  visibleEnd?: number;    // default 0
}): string

Mask the middle of a string, revealing only the first visibleStart and last visibleEnd characters.

mask('4242424242424242', { visibleEnd: 4 });
// β†’ '************4242'
mask('john@example.com', { visibleStart: 2 });
// β†’ 'jo**************'
πŸ”

For secret-grade masking that also hides length, see maskSecret in the main export.