pascalCase
The pascalCase utility transforms a string into PascalCase format (every word capitalized, no separators). It is typically used for naming classes, components, or TypeScript types.
Implementation
View Source Code
ts
import { normalizeCase } from './_caseUtils';
/**
* Converts a string to Pascal case.
*
* @example
* ```ts
* const text = 'Hello World';
* pascalCase(text) // 'HelloWorld';
* ```
*
* @param str - The string to convert.
*
* @returns The converted string.
*/
export function pascalCase(str: string): string {
return normalizeCase(str, ' ')
.replace(/(?:^|\s)(\w)/g, (_, char) => char.toUpperCase())
.replace(/\s+/g, '');
}Features
- Isomorphic: Works in both Browser and Node.js.
- Robust Word Splitting: Recognizes spaces, dashes, underscores, and dots as word boundaries.
- Consistent Output: Ensures the very first character is always uppercase.
API
ts
function pascalCase(input: string): string;Parameters
input: The string to transform.
Returns
- The transformed string in
PascalCase.
Examples
Basic Conversion
ts
import { pascalCase } from '@vielzeug/toolkit';
pascalCase('hello world'); // 'HelloWorld'
pascalCase('foo-bar'); // 'FooBar'
pascalCase('user_profile'); // 'UserProfile'
pascalCase('api.version'); // 'ApiVersion'Handling Case Transitions
ts
import { pascalCase } from '@vielzeug/toolkit';
pascalCase('camelCaseString'); // 'CamelCaseString'
pascalCase('web-api-v1'); // 'WebApiV1'
pascalCase(' spaced text '); // 'SpacedText'Implementation Notes
- Removes all non-alphanumeric separators.
- Capitalizes the first letter of every detected word and lowercases the rest (unless the word was already all caps, depending on specific heuristics).
- Throws
TypeErrorif the input is not a string.