-1

please help me to make this string "SeLamAT PAGi semua halOo"

become this "Selamat Pagi Semua Haloo"

i lil bit confuse make a function

  • Does this answer your question? [How do I make the first letter of a string uppercase in JavaScript?](https://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript) – sojin Feb 08 '22 at 16:40

1 Answers1

0

I've recently solved this problem, what I ended up using for this purpose is a regex.

Single line solution

const result = "SeLamAT PAGi semua halOo".replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase())

Alternative solution

function titleCase(input) {
   const splittedInput = input.toLowerCase().split(' ');
   for (const i = 0; i < splittedInput.length; i++) {
       splittedInput[i] = splittedInput[i].charAt(0).toUpperCase() + splittedInput[i].substring(1);     
   }
   return splittedInput.join(' '); 
}

const result = titleCase("SeLamAT PAGi semua halOo");
console.log(result);
desoss
  • 572
  • 4
  • 26
  • i am sorry but its not work at all – achmad robbi Feb 08 '22 at 16:45
  • @achmadrobbi notice that the replace method is not changing the string, you've to assign the result to a variable. I've updated the code so that this behavior would be more clear. – desoss Feb 08 '22 at 16:49