String Utilities
toPascalCase
Converts a string to PascalCase with proper acronym handling
Usage
import { toPascalCase } from '@/lib/to-pascal-case';
const result = toPascalCase("hello world-example");
console.log(result); // "HelloWorldExample"Installation
pnpm dlx shadcn@latest add https://utilcn.dev/r/to-pascal-case.jsonbunx --bun shadcn@latest add https://utilcn.dev/r/to-pascal-case.jsonnpx shadcn@latest add https://utilcn.dev/r/to-pascal-case.jsonyarn shadcn@latest add https://utilcn.dev/r/to-pascal-case.jsonParameters
| Parameter | Type | Description |
|---|---|---|
str | string | The input string |
Returns
string - The PascalCased string.
Examples
toPascalCase("hello world-example"); // "HelloWorldExample"
toPascalCase("XMLHttpRequest"); // "XmlHttpRequest"
toPascalCase("user_name"); // "UserName"
toPascalCase("api-response"); // "ApiResponse"
toPascalCase("HTML parser"); // "HtmlParser"Implementation
export function toPascalCase(str: string): string {
return (
str
// Split acronym groups into proper boundaries
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
// Split between lowercase/digit and uppercase
.replace(/([a-z\d])([A-Z])/g, '$1 $2')
// Normalize spaces/underscores/dashes
.replace(/[-_\s]+/g, ' ')
// Lowercase all to normalize
.toLowerCase()
// Capitalize every word
.replace(/\b\w/g, (c) => c.toUpperCase())
// Remove spaces
.replace(/\s+/g, '')
);
}