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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/** Capitalises first letter of each word in a string * * @param {string} string - text to capitalise. * @return {string} text with 1st letter of each word capitalised. */ function proper(string) { return string .toLowerCase() .split(" ") .map((val) => val[0].toUpperCase() + val.slice(1)) .join(" "); } console.log(proper("YAGISAN atode")); |
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:
1 2 |
const string = "THE data i WANT made PROPER"; let properString = proper(string); |
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.
Need help with Google Workspace development?
My team of experts can help you with all of your needs, from custom app development to integrations and security. We have a proven track record of success in helping businesses of all sizes get the most out of Google Workspace.
Schedule a free consultation today to discuss your needs and get started or learn more about our services here.
~Yagi
I keep getting an error at line 8 – string is undefined
What does your error message say?