I'm trying to capitalize the first letter of each word. But it just working first word only.
html
<ion-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(' ');
}
}
CodePudding user response:
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(' ');
CodePudding user response:
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(" ");
}