titleCase function
Converts a string to Title Case: words separated by spaces, each capitalized, acronyms kept.
ts
import { titleCase } from 'utils';Signature
ts
export function titleCase(input: string): stringParameters
| Name | Description |
|---|---|
input | The identifier or sentence to convert, in any case style. |
Returns
The title; '' when the input has no word.
Example
ts
titleCase('engine-room'); // 'Engine Room'
titleCase('maxSpeedGPS'); // 'Max Speed GPS'Tests
Line coverage: 100 %.
- ✅ converts "engine-room" to "Engine Room"
- ✅ converts "maxSpeedGPS" to "Max Speed GPS"
- ✅ converts "user_id" to "User Id"
- ✅ converts "HTTP status code" to "HTTP Status Code"
- ✅ converts "speed2" to "Speed 2"
- ✅ converts "" to ""
Source
src/string/title-case.ts (on GitHub)
Uses
capitalize: Upper-cases the first character of a string, even outside the basic Unicode plane.splitWords: Splits a string into words, whatever its case style (camelCase, kebab-case, snake_case, spaces…), in one pass.
Files it needs
src/string/title-case.ts imports, directly or not:
Source code
ts
import { capitalize } from './capitalize';
import { splitWords } from './split-words';
/**
* Converts a string to Title Case: words separated by spaces, each capitalized, acronyms kept.
*
* @param input - The identifier or sentence to convert, in any case style.
* @returns The title; `''` when the input has no word.
* @example
* titleCase('engine-room'); // 'Engine Room'
* titleCase('maxSpeedGPS'); // 'Max Speed GPS'
*/
export function titleCase(input: string): string {
return splitWords(input)
.map((word) => (word === word.toUpperCase() ? word : capitalize(word.toLowerCase())))
.join(' ');
}Test file
ts
import { titleCase } from './title-case';
describe(titleCase, () => {
it.for([
['engine-room', 'Engine Room'],
['maxSpeedGPS', 'Max Speed GPS'],
['user_id', 'User Id'],
['HTTP status code', 'HTTP Status Code'],
['speed2', 'Speed 2'],
['', ''],
] as const)('converts %j to %j', ([input, expected]) => {
expect(titleCase(input)).toBe(expected);
});
});Keywords: title, case, strings, function