capitalize
Capitalizes the first letter of a string. Converts the first character to uppercase while leaving the rest unchanged. Safely handles edge cases like empty strings and non-string inputs.
Installation
npx fragmen add string/capitalizeSource Code
/**
* Capitalizes the first letter of a string.
*
* Converts the first character to uppercase while leaving the rest unchanged.
* Safely handles edge cases like empty strings and non-string inputs.
*
* @tags pure, string-manipulation, formatting
* @param {string} str The string to capitalize.
* @returns {string} The string with the first letter capitalized, or empty string if invalid input.
*
* @example
* ```typescript
* capitalize('hello world'); // 'Hello world'
* capitalize('javaScript'); // 'JavaScript'
* capitalize('HTML'); // 'HTML'
* capitalize(''); // ''
* capitalize('a'); // 'A'
* ```
*/
export function capitalize(str: string): string {
if (typeof str !== 'string' || str.length === 0) {
return '';
}
return str.charAt(0).toUpperCase() + str.slice(1);
}
Examples
capitalize('hello world'); // 'Hello world'
capitalize('javaScript'); // 'JavaScript'
capitalize('HTML'); // 'HTML'
capitalize(''); // ''
capitalize('a'); // 'A'
Related Utilities
camel-case
stringConverts a string to camelCase. Transforms a string by removing spaces, underscores, and hyphens, then capitalizing the first letter of each word except the first one. Commonly used for JavaScript variable names, object properties, and function names.
kebab-case
stringConverts a string to kebab-case. Transforms a string by converting it to lowercase and replacing spaces, underscores, and camelCase boundaries with hyphens. Useful for creating URL slugs, CSS class names, and file names.
pad-end
stringPads the end of a string with another string until it reaches the target length. If padString is '', the original string is returned (mirrors native behavior).
pad-start
stringPads the start of a string with another string until it reaches the target length. If padString is '', the original string is returned (mirrors native behavior).
pascal-case
stringConverts a string to PascalCase. Transforms a string by removing spaces, underscores, and hyphens, then capitalizing the first letter of each word including the first one. Commonly used for class names, interface names, type names, and component names.
snake-case
stringConverts a string to snake_case. Transforms a string by converting it to lowercase and replacing spaces, hyphens, and camelCase boundaries with underscores. Commonly used for database column names, Python variables, and configuration keys.
Quick Actions
Tags
Parameters
strstringThe string to capitalize.
Returns
stringThe string with the first letter capitalized, or empty string if invalid input.