Search code examples
google-apps-scriptcapitalize

Apps script how to format a cell to Proper Text (Case)


I have a form coming to my sheet, and sometimes my customers enter the text in lower or upper case, and aso with line breaks

I have this code to make a cell UPPERCASE and remove the line breaks

var val = responses.getRange( i + 1 , 13).getValue();
    val = val.replace(/\n/g,", ");
    responses.getRange( i + 1 , 13).setValue(val.toUpperCase());

What I need is to make that cell to Proper Case, not UpperCase

For example if the text is "hello how ARE YOU" I want to convert to "Hello How Are You" or also to "Hello how are you"


Solution

    • You want to modify from hello how ARE YOU to Hello How Are You and Hello how are you using Google Apps Script.

    If my understanding is correct, how about this modification? Please think of this as just one of several answers.

    The flow of this modification is as follows.

    At first, the value is modified to lowercase.

    • At pattern 1, the first characters of each word modify to uppercase.
    • At pattern 2, the first character of value modifies uppercase.

    Sample script:

    var val = "hello how ARE YOU";
    
    var pattern1 = val.toLowerCase().replace(/\b[a-z]/ig, function(match) {return match.toUpperCase()});
    var pattern2 = val.toLowerCase().replace(/^[a-z]/i, function(match) {return match.toUpperCase()});
    
    console.log(pattern1) // Hello How Are You
    console.log(pattern2) // Hello how are you

    Reference:

    If you need other patterns, can you provide them?