Google Apps Script – Javascript: Emulate the “Proper” Google Sheets Function

Creating Google Sheets Proper in Javascript

Google Apps Script / Javascript

I just had a recent email from a reader who asked how to tidy up a user’s inputted name from say, a Google Form so that all the first letters of each work in the name are capitalised in the same way that the Google Sheets Proper function does.

I thought it would be a good idea to provide a quick reference for the reader and myself for future projects.

The Code

You can have a play with the cod by updating the proper function in JS Fiddle.

Running the Function

Copy and paste the function into your code. You can either do this as a runtime function or as a method inside another function. Make sure not to include the “console.log(...“.

The proper() function returns your updated string with the first letter of each word capitalised. So it is best to load the returned string into a new variable:

Code Breakdown

First, we transform the entire string to lowercase so that we have one consistent case. Line 8 

Next, we split the string into an array of individual words that are split by a space. Line 9

Once we have our array, we iterate over the array with the map method changing the zeroeth character of each string to uppercase. We then use slice which creates a shallow copy of the original string retaining all characters from the indicated start point which will be 1. This will create a shallow string of all remaining characters except the first letter. Then we use the plus (+) symbol to concatenate the capitalised first character to the lowercase remainder of the word. Line 10

Finally, we join our array of words back together using the join method which can take just the type of text separator. For us, this is just a space, " "Line 11

All these steps are placed in a large bracket so that return will carry out all lines of the task and then return the string that now has all the capitalised letters for each word in the string.

 

There are no doubt many versions of this out there. So feel free to choose your own. 

~Yagi

 

Leave a Reply