By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Capitalize the Words in JavaScript

+3 votes

Write a JavaScript function that capitalizes the given words. You need to make every word’s first letter – uppercase and all other letters – lowercase.

The input comes as a single string, containing words, separated by a space. Note: The words can contain any ASCII character. You need to affect only the letters.


Capitalize these words

Capitalize These Words

Was that Easy? tRY thIs onE for SiZe!

Was That Easy? Try This One For Size!

The output is the same string, however with all of its words capitalized.

asked in JavaScript category by user Jolie Ann

2 Answers

+2 votes

My js code:

function capW(input) {
    let array = input.toLowerCase().split(" ");
    let replacedFL = "";

    for (let i = 0; i < array.length; i++) {
        let firstLetter = array[i]
            .substr(0, 1)
        let replaced = array[i]
            .replace(array[i].substr(0, 1), firstLetter);

        replacedFL += replaced + " ";

capW("Was that Easy? tRY thIs onE for SiZe!");


answered by user andrew
0 votes

mine solution:

function solve(text) {
    let resultArray = text.split(" ");

    for (let i = 0; i < resultArray.length; i++) {
        resultArray[i] = resultArray[i].charAt(0).toUpperCase() + resultArray[i].substr(1).toLowerCase();

    console.log(resultArray.join(" "));

solve("Was that Easy? tRY thIs onE for SiZe!");


answered by user mitko