Skip to content

String Utilities

String helpers for stable element ids and URL slugs.

import { makeId, slugify } from '@msflib/typescript';

Table of Contents


makeId

makeId(component: string, id: string, key?: string | number | null): string;

Builds a readable id from its parts. With a truthy key the result is component-id-key. Otherwise a deterministic 4-digit suffix is derived from component-id (the sum of its character codes, mod 10000), so the same inputs always produce the same id - useful for id/htmlFor pairs and test selectors.

import { makeId } from '@msflib/typescript';

// With a specific key
const idWithKey = makeId('button', 'submit', 'icon');
console.log(idWithKey);
// "button-submit-icon"

// Without a key (generates a deterministic hash)
const idWithoutKey = makeId('input', 'username');
console.log(idWithoutKey);
// "input-username-1469"

Note

  • key is checked for truthiness, so 0 and '' are treated as "no key" and fall back to the hash suffix: makeId('row', 'item', 0) does not return "row-item-0".
  • The suffix is a simple checksum, not a unique id: different inputs can collide (e.g. anagrams). Pass a key when you need uniqueness.

slugify

slugify(str: string): string;

Lowercases and trims the string, replaces whitespace runs with -, removes every character that is not a word character (A-Z a-z 0-9 _) or -, then collapses repeated -.

import { slugify } from '@msflib/typescript';

const title = 'My Awesome Post & New Features!';
const slug = slugify(title);

console.log(slug);
// "my-awesome-post-new-features"

Note

  • Non-ASCII letters are removed, not transliterated: slugify('Héllo') gives "hllo".
  • Underscores are kept, and leading/trailing hyphens are not stripped: slugify('-a-') gives "-a-".

See also: Object utilities · Function utilities