I can write this code in a simpler way but I want to write it as a function based code. I am looking to change the starting letter of each word in a string to uppercase.Please help!!
function convertuc(str) {
let arr = str.toLowerCase().split(" ");
for (let s of arr){
let arr2 = arr.map(s.charAt(0).toUpperCase() + s.substring(1)).join(" ");
}
return arr2
};
console.log(convertuc("convert the first letter to upper case")); // Test//
-
4Possible duplicate of How do I make the first letter of a string uppercase in JavaScript?Tim Biegeleisen– Tim Biegeleisen2018年11月02日 00:31:21 +00:00Commented Nov 2, 2018 at 0:31
2 Answers 2
You're almost there. You don't need a for loop since you're already using map (which does the iteration for you and builds a new array by transforming each string in arr to a new one based on the function provided).
function convertuc(str) {
let arr = str.toLowerCase().split(" ");
let arr2 = arr.map(s => s.charAt(0).toUpperCase() + s.substring(1)).join(" ");
return arr2; // note that arr2 is a string now because of .join(" ")
};
console.log(convertuc("convert the first letter to upper case"));
answered Nov 2, 2018 at 0:30
Sign up to request clarification or add additional context in comments.
1 Comment
shine12
ok, thank, all I need was to get rid of the second function and define s as (s=>).
What about to use pure CSS?
p {
text-transform: capitalize;
}
<p>this is a simple sentence.</p>
answered Nov 2, 2018 at 0:51
Comments
lang-js