Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions String/TitleCase.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* @function titleCase
* @description Converts a string to title case where the first letter
* of each word is capitalized and the rest are lowercase.
* @param {string} str - The input string
* @returns {string} - The title cased string
* @see https://en.wikipedia.org/wiki/Title_case
* @example titleCase("hello world") => "Hello World"
* @example titleCase("the quick brown fox") => "The Quick Brown Fox"
* @example titleCase("HELLO WORLD") => "Hello World"
*/
const titleCase = (str) => {
if (typeof str !== 'string') {
throw new TypeError('Input must be a string')
}
return str
.toLowerCase()
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')
}

export { titleCase }
39 changes: 39 additions & 0 deletions String/test/TitleCase.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { titleCase } from '../TitleCase.js'

describe('titleCase', () => {
test("titleCase('hello world') returns 'Hello World'", () => {
expect(titleCase('hello world')).toBe('Hello World')
})

test("titleCase('the quick brown fox') returns 'The Quick Brown Fox'", () => {
expect(titleCase('the quick brown fox')).toBe('The Quick Brown Fox')
})

test("titleCase('HELLO WORLD') returns 'Hello World'", () => {
expect(titleCase('HELLO WORLD')).toBe('Hello World')
})

test("titleCase('') returns ''", () => {
expect(titleCase('')).toBe('')
})

test('titleCase single word', () => {
expect(titleCase('javascript')).toBe('Javascript')
})

test('titleCase handles multiple spaces', () => {
expect(titleCase('hello world')).toBe('Hello World')
})

test('titleCase handles mixed case', () => {
expect(titleCase('hElLo WoRlD')).toBe('Hello World')
})

test('throws TypeError for non-string input', () => {
expect(() => titleCase(123)).toThrow(TypeError)
})

test('throws TypeError for null', () => {
expect(() => titleCase(null)).toThrow(TypeError)
})
})
Loading