shine12
shine12

Reputation: 37

Convert first letter of each word in a string to Uppercase in JavaScript

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//

Upvotes: 2

Views: 510

Answers (2)

Pablo Darde
Pablo Darde

Reputation: 6402

What about to use pure CSS?

p {
  text-transform: capitalize;
}
<p>this is a simple sentence.</p>

Upvotes: 4

slider
slider

Reputation: 12990

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

Upvotes: 4

Related Questions