settingsAccountsettings
Menusettings

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.

Examples:

Input:
Capitalize these words

Output:
Capitalize These Words


Input:
Was that Easy? tRY thIs onE for SiZe!

Output:
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)
            .toUpperCase();
        let replaced = array[i]
            .replace(array[i].substr(0, 1), firstLetter);

        replacedFL += replaced + " ";
    }
    console.log(replacedFL);
}

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
...