Search code examples
uppercaselowercase

Make lower case to a specific latter in javascript


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

become this "Selamat Pagi Semua Haloo"

i lil bit confuse make a function


Solution

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