0

I'm trying to capitalize the first letter of each word. But it just working first word only.

html

<ion-input class="add-category-input" [(ngModel)]="addcategory.setting.category" (ngModelChange)="transform(addcategory.setting.category)"></ion-input>

Ts

transform(value: string) {
    const inputText = value.toLowerCase().split(' ');
    console.log(inputText);
    for (var i = 0; i < inputText.length; i++) {
      console.log(inputText.length);
      inputText[i] = inputText[i].charAt(0).toUpperCase() + inputText[i].slice(1);
      console.log(inputText[i]);
      return this.addcategory.setting.category = inputText.join(' ');
    }
  }
Fash
  • 309
  • 1
  • 13
  • 3
    While there is already an accepted answer, I would like to note that your solution was only returning the first word because you had the return statement within the `for` loop, if you would move it outside the `for` loop it would had worked. – David Fontes Feb 17 '22 at 10:33
  • 1
    Does this answer your question? [How can I capitalize the first letter of each word in a string using JavaScript?](https://stackoverflow.com/questions/32589197/how-can-i-capitalize-the-first-letter-of-each-word-in-a-string-using-javascript) – habla2019 Feb 17 '22 at 11:24

2 Answers2

3

You can use this one-liner:

string.split(' ').map(word => word[0].toUpperCase() + word.substring(1)).join(' ');

What it does:

// splits the string at the spaces
const splitArr = string.split(' ') 

// loop over the array of words, and return your desired result
// Desired result is: capitalize the first letter and append the rest of the word.
const capitalizedArr = splitArr.map(word => word[0].toUpperCase() + word.substring(1))

// join the words from the capitalized array with a space.
const result = capitalizedArr.join(' ');
jolo
  • 605
  • 1
  • 5
  • 12
1

Try this:

function capitalizeFirstLetter(str) {
    const arr = str.split(" ");

    for (var i = 0; i < arr.length; i++) {
        arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
    }

    return arr.join(" ");
}
Yasin BARAN
  • 239
  • 3
  • 11