Formatting phone number in place in sheet cell

假装没事ソ 提交于 2020-04-30 09:23:28

问题


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;

I also asked this question Validate phonenumbers to specific format using Google Sheet formula and obviously it can be done as a formula in an adjacent column. However in my case each row is created by a post request to google sheets from a submitted form and I'd like to format the phone number IN PLACE (ie in the cell) to look like 1aaabbbcccc. Is this possible?

but I'd like to make the sheet do this. Is this possible ?


回答1:


  • For Google Spreadsheet, you want to convert 402-333-4444 to 14023334444 by adding 1.
  • You want to achieve this using Google Apps Script.

In order to achieve your goal, I would like to propose to overwrite the converted values to the cells.

Sample script:

In this sample script, it supposes that the values are put to the cells "D2:D". When you run the script, the cells "A2:A" is overwritten by the converted values.

function myFunction() {
  const sheetName = "Sheet1"; // Please set the sheet name.

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const range = sheet.getRange(2, 4, sheet.getLastRow() - 1, 1);  // Column "D"
  const values = range.getValues();
  const converted = values.map(([v]) => {
    if (/\d{3}-\d{3}-\d{4}/.test(v)) {
      let temp = v.replace(/-/g, "");
      console.log(v.charAt(0))
      const tempV = v.charAt(0) != 1 ? 1 + temp : temp;
      return [tempV.length == 11 ? tempV : v];
    }
    return [v];
  });
  range.setValues(converted);
}

Note:

  • When you want to also convert 402 333 4444 to 14023334444, please modify as follows.

    • From

      if (/\d{3}-\d{3}-\d{4}/.test(v)) {
        let temp = v.replace(/-/g, "");
      
    • To

      if (/\d{3}-\d{3}-\d{4}|\d{3} \d{3} \d{4}/.test(v)) {
        let temp = v.replace(/-| /g, "");
      


来源:https://stackoverflow.com/questions/61279657/formatting-phone-number-in-place-in-sheet-cell

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