google-apps-scriptcapitalize

Google Script Apps - Capitalize first letter of each word of input string in cell


I am looking for a solution that capitalizes each word of the input string to cell seperated by blank space or dot (similar to proper function). I know it is broken but what I tried so far:

    /*Capitalize Firt Letter of Each Word of input String in Cell*/
  if(activeRow > 1 && activeCol == 3 && ss.getSheetName() == validSheet && activeCell.isBlank() == false)
  { 
    var inputVal = activeCell.getValue().toString();
    Logger.log(inputVal);
    activeCell.setFormulaR1C1("=PROPER("+inputVal+")");
  }

Example:

Input for cell A2:

this tExt neEds to be fixed

Output (Desired Result) for cell A2:

This Text Needs To Be Fixed

I noticed that the proper function won't work because it requires cell value in it.


Solution

  • Here's a function that takes a string and capitalizes the first letter of each word:

    function capitalizePhrase(phrase) {
      var reg = /\b(\w)/g;
      function replace(firstLetters) {
        return firstLetters.toUpperCase();
      }
      capitalized = phrase.replace(reg, replace);
      return capitalized;
    }
    

    which you could then use like this:

    var inputVal = activeCell.getValue().toString();
    var outputVal = capitalizePhrase(inputVal);
    activeCell.setValue(outputVal);
    

    Edit - if you also want to set other letters in the word to lower case, you can use this function instead:

    function properCase(phrase) {
      var regFirstLetter = /\b(\w)/g;
      var regOtherLetters = /\B(\w)/g;
      function capitalize(firstLetters) {
        return firstLetters.toUpperCase();
      }
      function lowercase(otherLetters) {
        return otherLetters.toLowerCase();
      }
      var capitalized = phrase.replace(regFirstLetter, capitalize);
      var proper = capitalized.replace(regOtherLetters, lowercase);
    
      return proper;
    }