From 28716c7b5a523e463ceccea627f39eb6e2c59c16 Mon Sep 17 00:00:00 2001 From: ztimson Date: Wed, 15 Apr 2026 21:59:42 -0400 Subject: [PATCH] Added titleCase helper --- package.json | 2 +- src/string.ts | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 0d867de..0bae84e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.29.3", + "version": "0.29.4", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/string.ts b/src/string.ts index 2ee9969..e75303e 100644 --- a/src/string.ts +++ b/src/string.ts @@ -241,7 +241,6 @@ export function snakeCase(str?: string): string { return wordSegments(str).map(w => w.toLowerCase()).join("_"); } - /** * Splice a string together (Similar to Array.splice) * @@ -257,6 +256,20 @@ export function strSplice(str: string, start: number, deleteCount: number, inser return before + insert + after; } +function titleCase(str: string) { + // Normalize separators: replace underscores and hyphens with spaces + let normalizedStr = str.replace(/(_|-)/g, ' '); + // Handle CamelCase/PascalCase boundaries: insert a space before capital letters + normalizedStr = normalizedStr.replace(/([a-z])([A-Z])/g, '$1 $2'); + // Lowercase the whole string, split by any whitespace, and capitalize each word + let words = normalizedStr.toLowerCase().split(/\s+/).filter(Boolean); + const titledWords = words.map(word => { + if (word.length === 0) return ''; + return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); + }); + return titledWords.join(' '); +} + /** * Find all substrings that match a given pattern. *