Validate phonenumbers to specific format using Google Sheet formula

梦想的初衷 提交于 2020-04-18 05:43:27

问题


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")&regexreplace(""&D2,"[^0-9]",""))=11,
if(left(regexreplace(""&D2,"[^0-9]",""))="1","","1")&regexreplace(""&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")&regexreplace(""&D2:D,"[^0-9]",""))=11,
if(left(regexreplace(""&D2:D,"[^0-9]",""))="1","","1")&regexreplace(""&D2:D,"[^0-9]",""),"INVALID")))


来源:https://stackoverflow.com/questions/60156027/validate-phonenumbers-to-specific-format-using-google-sheet-formula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!