Fash
Fash

Reputation: 231

Capitalize the first letter each word

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(' ');
    }
  }

Upvotes: 0

Views: 3176

Answers (3)

Siraj Ali
Siraj Ali

Reputation: 604

In angular

Use TitleCasePipe which Capitalizes the first letter of each word.

{{ value_expression | titlecase }}

How to apply it in html tag, check the below example

<h5>{{ data.title | titlecase }} :</h5>

Upvotes: 1

jolo
jolo

Reputation: 660

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(' ');

Upvotes: 3

Yasin BARAN
Yasin BARAN

Reputation: 257

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(" ");
}

Upvotes: 1

Related Questions