问题
I'm working with google sheets and would like to convert US phone numbers to the format:
1xxxyyyzzzz
eg 402-333-4444 should be turned into 14023334444
I have an apps script validator function which does this:
var numbers = 'INVALID'
if ( parsed_body.hasOwnProperty('PHONE') ) {
var phone = parsed_body['PHONE'].toString();
Logger.log(parsed_body);
numbers = phone.replace(/[^0-9]/g, "");
var firstChar = numbers.charAt(0);
if ( firstChar !== '1'){ numbers = '1'+ numbers}
Logger.log(numbers);
if ( numbers.length !== 11){ numbers = 'NOTELEVEN'};
}
parsed_body['PHONE']=numbers;
but I'd like to make the sheet do this. Is this possible ?
回答1:
It works out to quite a long formula if you do it in a single formula, because you have to keep repeating the previous steps, unlike in the script version:
=if(len(if(left(regexreplace(""&D2,"[^0-9]",""))="1","","1")®exreplace(""&D2,"[^0-9]",""))=11,
if(left(regexreplace(""&D2,"[^0-9]",""))="1","","1")®exreplace(""&D2,"[^0-9]",""),"INVALID")
May be changed to an array formula:
=ArrayFormula(if(D2:D="","",if(len(if(left(regexreplace(""&D2:D,"[^0-9]",""))="1","","1")®exreplace(""&D2:D,"[^0-9]",""))=11,
if(left(regexreplace(""&D2:D,"[^0-9]",""))="1","","1")®exreplace(""&D2:D,"[^0-9]",""),"INVALID")))
来源:https://stackoverflow.com/questions/60156027/validate-phonenumbers-to-specific-format-using-google-sheet-formula