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// 
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"));

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.