EXERCISE · AlgoCasts
Capitalize
Write a function that accepts a string. The function should capitalize the first letter of each word in the string then return the capitalized string.
Directions
Directions
Write a function that accepts a string. The function should capitalize the first letter of each word in the string then return the capitalized string.
Examples#
JS
capitalize('a short sentence') --> 'A Short Sentence'capitalize('a lazy fox') --> 'A Lazy Fox'capitalize('look, it is working!') --> 'Look, It Is Working!'Try it first#
Copy the stub, make the 3 tests pass on your machine, then open the solution. The reveal is remembered per page in this browser.
JSexercises/capitalize/index.js
function capitalize(str) {} module.exports = capitalize;Solution#
JScompleted_exercises/capitalize/index.js
function capitalize(str) { let result = str[0].toUpperCase(); for (let i = 1; i < str.length; i++) { if (str[i - 1] === ' ') { result += str[i].toUpperCase(); } else { result += str[i]; } } return result;} module.exports = capitalize;function capitalize(str) { const words = []; for (let word of str.split(' ')) { words.push(word[0].toUpperCase() + word.slice(1)); } return words.join(' ');}const capitalize = require('./index'); test('Capitalize is a function', () => { expect(typeof capitalize).toEqual('function');}); test('capitalizes the first letter of every word in a sentence', () => { expect(capitalize('hi there, how is it going?')).toEqual( 'Hi There, How Is It Going?' );}); test('capitalizes the first letter', () => { expect(capitalize('i love breakfast at bill miller bbq')).toEqual( 'I Love Breakfast At Bill Miller Bbq' );}); Verbatim from the repo at 30cf7634. Alternate tabs are the commented-out solutions with the leading // removed and nothing else changed. Run the tests locally with npx jest capitalize inside the fork.
See also