You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script手机号前缀插入规则实现及代码修改求助

Google Apps Script 电话号码格式转换优化

功能需求

  • 若电话号码字符串以数字“7”开头,在开头插入“+44”
  • 若电话号码字符串以数字“8”开头,在开头插入“+353”
  • 若电话号码字符串已以“+”开头,保持原内容不修改
  • 同时移除号码中的“-”符号

现有待优化脚本

let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1')
let lastRow = ss.getLastRow();
let numOld = ss.getRange(2, 12,lastRow-1,1).getValues();
//var paymentTypeRange = sheet.getRange(2, 14, sheet.getLastRow() -1, sheet.getLastColumn()).getValues(); 

numOld.forEach((r,i) =>{ 

console.log(r[0])
  let newnum = []

  //delete "-" in phone number and push in newnum array
  //Or use other REGEX in replace, it's up to you.
  numOld.map(data => {
    newnum.push(data[0].toString().replace(/[-]/g, ''))
  })
  if(  r[0].match(/^7/) ){
  //push "+44" in after position 0 in text and then join with ''
  let pushdatanum = newnum.map(d => {
    return [d.slice(0, 0), '+44', d.slice(0)].join('');
  })

ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1')
  
  //insert back to Sheet1 begin at row2 col3, numRow from pushdatanum.lenght, numColum from pushdatanum[0]. 
  //length
  ss.getRange(2, 3,pushdatanum.length, pushdatanum[0].length).setValues(pushdatanum);
  }
  if(  r[0].match(/^8/) ){
  //push "+353" in after position 0 in text and then join with ''
  let pushdatanum2 = pushdatanum.map(d => {
    return [[d.slice(0, 0), '+353', d.slice(0)].join('')];
  })
  

  ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1')
  
  //insert back to Sheet1 begin at row2 col3, numRow from pushdatanum2.lenght, numColum from pushdatanum2[0]. 
  //length
  ss.getRange(2, 3,pushdatanum2.length, pushdatanum2[0].length).setValues(pushdatanum2);
}})

return false
}

优化后的脚本

function formatPhoneNumbers() {
  const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  const lastRow = ss.getLastRow();
  // 获取L列(第12列)从第2行开始的所有数据
  const numOld = ss.getRange(2, 12, lastRow - 1, 1).getValues();
  
  // 处理每一个电话号码
  const formattedNumbers = numOld.map(row => {
    let phone = row[0].toString().replace(/[-]/g, ''); // 移除所有"-"符号
    
    // 根据开头字符判断格式
    if (phone.startsWith('+')) {
      return [phone]; // 已带+号,直接返回
    } else if (phone.startsWith('7')) {
      return [`+44${phone}`];
    } else if (phone.startsWith('8')) {
      return [`+353${phone}`];
    } else {
      return [phone]; // 其他情况保持原样
    }
  });
  
  // 将处理后的数据写入C列(第3列)从第2行开始的位置
  ss.getRange(2, 3, formattedNumbers.length, 1).setValues(formattedNumbers);
}

优化说明

  1. 逻辑简化:移除原脚本中冗余的循环嵌套,用一次map完成所有格式转换,避免重复遍历数据
  2. 性能提升:减少对Spreadsheet服务的重复调用(原脚本多次重新获取Sheet对象),仅在开头获取一次,结尾一次性写入结果
  3. 可读性增强:使用startsWith替代正则匹配,逻辑更直观;添加清晰注释说明每一步操作
  4. 鲁棒性优化:增加对非7/8/+开头号码的兼容,此类号码保持原样
  5. 格式规范:确保返回数组符合setValues要求的二维数组格式,避免写入错误

内容的提问来源于stack exchange,提问作者Les

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 11:47:51