capitalize function
Upper-cases the first character of a string, even outside the basic Unicode plane.
ts
import { capitalize } from 'utils';Signature
ts
export function capitalize(input: string): stringParameters
| Name | Description |
|---|---|
input | The string. |
Returns
The string with its first character in upper case.
Example
ts
capitalize('hello world'); // 'Hello world'
capitalize('élan'); // 'Élan'Tests
Line coverage: 100 %.
- ✅ capitalizes "hello world" as "Hello world"
- ✅ capitalizes "Hello" as "Hello"
- ✅ capitalizes "hELLO" as "HELLO"
- ✅ capitalizes "élan" as "Élan"
- ✅ capitalizes "1st" as "1st"
- ✅ capitalizes "" as ""
- ✅ capitalizes "𐐨x" as "𐐀x"
Source
src/string/capitalize.ts (on GitHub)
Used by
camelCase: Converts a string to camelCase; acronyms are words (XMLHttpRequest→xmlHttpRequest).pascalCase: Converts a string to PascalCase: words joined, each capitalized, the rest in lower case.sentenceCase: Converts an identifier to a sentence, to turn a key into a label: the first word capitalized, the others in lower case, acronyms kept.titleCase: Converts a string to Title Case: words separated by spaces, each capitalized, acronyms kept.trainCase: Converts a string to Train-Case: capitalized words joined with-, as in HTTP header names.
Source code
ts
/**
* Upper-cases the first character of a string, even outside the basic Unicode plane.
*
* @param input - The string.
* @returns The string with its first character in upper case.
* @example
* capitalize('hello world'); // 'Hello world'
* capitalize('élan'); // 'Élan'
*/
export function capitalize(input: string): string {
const first = input.codePointAt(0);
if (first === undefined) {
return input;
}
const firstCharacter = String.fromCodePoint(first);
return firstCharacter.toUpperCase() + input.slice(firstCharacter.length);
}Test file
ts
import { capitalize } from './capitalize';
describe(capitalize, () => {
it.for([
['hello world', 'Hello world'],
['Hello', 'Hello'],
['hELLO', 'HELLO'],
['élan', 'Élan'],
['1st', '1st'],
['', ''],
['\u{10428}x', '\u{10400}x'],
] as const)('capitalizes %j as %j', ([input, expected]) => {
expect(capitalize(input)).toBe(expected);
});
});Keywords: capitalize, strings, function