2

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//
asked Nov 2, 2018 at 0:28
1

2 Answers 2

5

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

ok, thank, all I need was to get rid of the second function and define s as (s=>).
4

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.