I'm trying replace first letter of the text in a cell to upper case when a cell edited. For that I'm using onEdit
script trigger:
function onEdit(e)
{
e.range.setValue(e.range.getValue().replace(/^./, a => a.toUpperCase()));
}
It works well, until I try undo in the spreadsheet, than onEdit
fires again and replaces the text again.
So is there a better way to achieve this?
CodePudding user response:
First Letter to UpperCase
function onEdit(e) {
//e.source.toast('Entry')
const sh = e.range.getSheet();
if(sh.getName() == 'Sheet0' && e.range.columnStart == 1 && e.range.rowStart > 1 && e.value) {
//e.source.toast('Flag1')
e.range.setValue(e.value.replace(/^\s*(\w)/, a => a.toUpperCase()));
}
}
CodePudding user response:
Apparently the event object that onEdit
receives contains value
and oldValue
properties, they both set to undefined
when used undo.
So this seems to be working much better (it also ignores white space infront):
function onEdit(e)
{
if (e.value)
{
const val = e.value.replace(/^\s*./, a => a.toUpperCase());
if (val !== e.value)
e.range.setValue(val);
}
}
It still not a perfect solution, because it has delay in the execution and also it might skip cells if multiple edits in multiple cells were done in short period of time.