【问题标题】:Correct the phone number format using regex in JS在 JS 中使用正则表达式更正电话号码格式
【发布时间】:2021-01-21 01:20:23
【问题描述】:

我让用户输入数字

01122449000

  • 501122449000
  • 5 011 223 39000 01122449000
  • 501 12244 90 00

正确的格式是 +5最后 11 位数字>

我试过了

"+5" + tel.match(/\d+/g)[0]

Butists 给出错误的结果

【问题讨论】:

    标签: javascript regex google-apps-script


    【解决方案1】:

    您可以尝试去掉空格,然后只保留第一个数字和最后 11 个数字:

    var phone = "5 011 223 39000 01122449000";
    var output = phone.replace(/\s+/g, "").replace(/^(\d)\d*(\d{11})$/, "+$1$2");
    console.log(phone + "\n" + output);
    
    if (/^\+5\d{11}$/.test(output)) {
        console.log("valid phone number");
    }
    else {
        console.log("invalid phone number");
    }

    【讨论】:

      【解决方案2】:
      function getFormattedPhone(a) {
          if (a) return (a = a.match(/\d+/g)) ? "'+2" + a.join("").substr(-11) : ""
      };
      

      这对我有用。

      【讨论】:

        猜你喜欢
        • 2011-09-15
        • 2019-05-23
        • 2014-10-04
        • 2016-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-23
        • 2014-02-15
        相关资源
        最近更新 更多