File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * @function titleCase
3+ * @description Converts a string to title case where the first letter
4+ * of each word is capitalized and the rest are lowercase.
5+ * @param {string } str - The input string
6+ * @returns {string } - The title cased string
7+ * @see https://en.wikipedia.org/wiki/Title_case
8+ * @example titleCase("hello world") => "Hello World"
9+ * @example titleCase("the quick brown fox") => "The Quick Brown Fox"
10+ * @example titleCase("HELLO WORLD") => "Hello World"
11+ */
12+ const titleCase = ( str ) => {
13+ if ( typeof str !== 'string' ) {
14+ throw new TypeError ( 'Input must be a string' )
15+ }
16+ return str
17+ . toLowerCase ( )
18+ . split ( ' ' )
19+ . map ( ( word ) => word . charAt ( 0 ) . toUpperCase ( ) + word . slice ( 1 ) )
20+ . join ( ' ' )
21+ }
22+
23+ export { titleCase }
Original file line number Diff line number Diff line change 1+ import { titleCase } from '../TitleCase.js'
2+
3+ describe ( 'titleCase' , ( ) => {
4+ test ( "titleCase('hello world') returns 'Hello World'" , ( ) => {
5+ expect ( titleCase ( 'hello world' ) ) . toBe ( 'Hello World' )
6+ } )
7+
8+ test ( "titleCase('the quick brown fox') returns 'The Quick Brown Fox'" , ( ) => {
9+ expect ( titleCase ( 'the quick brown fox' ) ) . toBe ( 'The Quick Brown Fox' )
10+ } )
11+
12+ test ( "titleCase('HELLO WORLD') returns 'Hello World'" , ( ) => {
13+ expect ( titleCase ( 'HELLO WORLD' ) ) . toBe ( 'Hello World' )
14+ } )
15+
16+ test ( "titleCase('') returns ''" , ( ) => {
17+ expect ( titleCase ( '' ) ) . toBe ( '' )
18+ } )
19+
20+ test ( 'titleCase single word' , ( ) => {
21+ expect ( titleCase ( 'javascript' ) ) . toBe ( 'Javascript' )
22+ } )
23+
24+ test ( 'titleCase handles multiple spaces' , ( ) => {
25+ expect ( titleCase ( 'hello world' ) ) . toBe ( 'Hello World' )
26+ } )
27+
28+ test ( 'titleCase handles mixed case' , ( ) => {
29+ expect ( titleCase ( 'hElLo WoRlD' ) ) . toBe ( 'Hello World' )
30+ } )
31+
32+ test ( 'throws TypeError for non-string input' , ( ) => {
33+ expect ( ( ) => titleCase ( 123 ) ) . toThrow ( TypeError )
34+ } )
35+
36+ test ( 'throws TypeError for null' , ( ) => {
37+ expect ( ( ) => titleCase ( null ) ) . toThrow ( TypeError )
38+ } )
39+ } )
You can’t perform that action at this time.
0 commit comments