Capitalize a String
capitalizeStringβ
The capitalizeString
function converts the first letter of a given string to uppercase while keeping the rest lowercase (unless otherwise specified). It provides flexible options to capitalize all letters, each wordβs first letter, or retain the original casing.
Function Signatureβ
function capitalizeString(string: string, options?: CapitalizeOptions): string;
Parametersβ
string
: The string to capitalize.options
(optional): Customization options for capitalization:capitalizeEachFirst
(boolean): Capitalizes the first letter of each word. Defaults tofalse
.capitalizeAll
(boolean): Converts the entire string to uppercase. Defaults tofalse
.lowerCaseRest
(boolean): Ensures all characters except the first are lowercase. Defaults totrue
.
Return Valueβ
Returns a string with capitalization applied based on the provided options:
- Default behavior: Only the first letter is capitalized, and the rest is lowercase.
- If
capitalizeEachFirst: true
, the first letter of every word is capitalized. - If
capitalizeAll: true
, the entire string is converted to uppercase. - If
lowerCaseRest: false
, the remaining letters retain their original casing.
Example Usageβ
Importβ
import { capitalizeString } from 'nhb-toolbox';
Basic Capitalizationβ
capitalizeString('hello world');
// Output: 'Hello world'
Capitalizing Each Wordβ
capitalizeString('hello world', { capitalizeEachFirst: true });
// Output: 'Hello World'
Converting Entire String to Uppercaseβ
capitalizeString('hello world', { capitalizeAll: true });
// Output: 'HELLO WORLD'
Keeping the Rest of the String's Case Intactβ
capitalizeString('hello WORLD', { lowerCaseRest: false });
// Output: 'Hello WORLD'
Edge Cases Handledβ
- If the input is an empty string or not a valid string, it returns an empty string.
- It correctly handles strings with leading/trailing whitespace.
- Supports punctuation and special characters while preserving them.
Typesβ
CapitalizeOptions
β
interface CapitalizeOptions {
capitalizeEachFirst?: boolean;
capitalizeAll?: boolean;
lowerCaseRest?: boolean;
}
Conclusionβ
The capitalizeString
function provides a versatile way to format text with precise capitalization rules, handling various cases such as entire-string uppercase, word-based capitalization, and preservation of casing when needed.