简体   繁体   中英

How can I automatically remove extra characters from phone numbers in a specific column on Google Sheets?

I have a Google spreadsheet where multiple users input 10 digit phone numbers on column D. I would like all phone numbers to be formatted with ONLY the 10 digits and nothing extra. No spaces, parenthesis, or hyphens. How can this be accomplished automatically as soon as a user inputs the number? Currently I am manually doing this by selecting the entire column and using the Find and Replace function. I have attempted to record a macro using this but have not had any luck.

Example Inputs:
123-456-7890
(123)456-7890
123 456 7890

Example Output Result:
1234567890

You can also do it by a single formula

=REGEXREPLACE(A2,"[^0-9]","")

I believe your goal as follows.

  • You want to convert the following situation using Google Apps Script.

    • From

       123-456-7890 (123)456-7890 123 456 7890
    • To

       1234567890
  • You want to run the script when the value is put to the column "D".

In this case, I would like to run the function using OnEdit trigger as the simple trigger. And, in order to replace the value, I would like to propose to use TextFinder. The sample script is as follows.

Sample script:

Please copy and paste the following script to the script editor of Google Spreadsheet. And, please set the sheet name of the sheet you want to use. In order to run the script, please put the value to the column "D".

function onEdit(e) {
  const sheetName = "Sheet1"; // Please set the sheet name.
  const range = e.range;
  if (range.getSheet().getSheetName() != sheetName || range.columnStart != 4) return;
  range.createTextFinder("[-() ]").useRegularExpression(true).replaceAllWith("");
}
  • In this script, when above values of 123-456-7890 , (123)456-7890 , 123 456 7890 are put to the column "D", those values are converted to 1234567890 .

Note:

  • This script is run by the simple trigger of OnEdit. So when you directly run the script with the script editor, an error like TypeError: Cannot read property 'range' of undefined occurs. Please be careful this.

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM