Reputation: 127
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.
Upvotes: 1
Views: 7023
Reputation: 1
I did another way, I don't know if it's better but at least, I find it simplier :
// Cap the first letter and minimize all the others
function CapStrings(txt) {
var firstLetter = txt.slice(0,1).toUpperCase();
var othersLetters = txt.slice(1).toLowerCase();
var newTxt = firstLetter + othersLetters;
return newTxt;
}
Upvotes: 0
Reputation: 4537
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;
}
Upvotes: 5