简体   繁体   English

在JS中使用正则表达式更正电话号码格式

[英]Correct the phone number format using regex in JS

I have users entering the numbers as我有用户输入数字

01122449000 01122449000

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

The correct format is +5< last 11 digits >正确的格式是+5<最后11位数字>

I have tried with我试过

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

Butists giving incorrect results Butists给出不正确的结果

You could try stripping whitespace then retaining just the first digit and final 11 digits:您可以尝试去除空格,然后只保留第一位和最后 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"); }

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

This worked for me.这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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