用 Javascript 重新格式化美国电话号码的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8358084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular Expression to reformat a US phone number in Javascript
提问by Matt K
I'm looking to reformat (replace, not validate - there are many references for validating) a phone number for display in Javascript. Here's an example of some of the data:
我正在寻找重新格式化(替换,而不是验证 - 有许多验证参考)要在 Javascript 中显示的电话号码。以下是一些数据的示例:
- 123 4567890
- (123) 456-7890
- (123)456-7890
- 123 456 7890
- 123.456.7890
- (blank/null)
- 1234567890
- 123 4567890
- (123) 456-7890
- (123)456-7890
- 123 456 7890
- 123.456.7890
- (空白/空)
- 1234567890
Is there an easy way to use a regular expression to do this? I'm looking for the best way to do this. Is there a better way?
有没有一种简单的方法可以使用正则表达式来做到这一点?我正在寻找最好的方法来做到这一点。有没有更好的办法?
I want to reformat the number to the following: (123) 456-7890
我想将数字重新格式化为以下内容: (123) 456-7890
回答by maerics
Assuming you want the format "(123) 456-7890
":
假设您想要格式“ (123) 456-7890
”:
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
if (match) {
return '(' + match[1] + ') ' + match[2] + '-' + match[3]
}
return null
}
Here's a version that allows the optional +1
international code:
这是一个允许可选+1
国际代码的版本:
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/)
if (match) {
var intlCode = (match[1] ? '+1 ' : '')
return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('')
}
return null
}
formatPhoneNumber('+12345678900') // => "+1 (234) 567-8900"
formatPhoneNumber('2345678900') // => "(234) 567-8900"
回答by ioseb
Possible solution:
可能的解决方案:
function normalize(phone) {
//normalize string and remove all unnecessary characters
phone = phone.replace(/[^\d]/g, "");
//check if number length equals to 10
if (phone.length == 10) {
//reformat and return phone number
return phone.replace(/(\d{3})(\d{3})(\d{4})/, "() -");
}
return null;
}
var phone = '(123)4567890';
phone = normalize(phone); //(123) 456-7890
回答by Sean Bright
var x = '301.474.4062';
x = x.replace(/\D+/g, '')
.replace(/(\d{3})(\d{3})(\d{4})/, '() -');
alert(x);
回答by David Baucum
This answer borrows from maerics' answer. It differs primarily in that it accepts partially entered phone numbers and formats the parts that have been entered.
这个答案借用了 maerics 的答案。它的主要区别在于它接受部分输入的电话号码并格式化已输入的部分。
phone = value.replace(/\D/g, '');
const match = phone.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
if (match) {
phone = `${match[1]}${match[2] ? ' ' : ''}${match[2]}${match[3] ? '-' : ''}${match[3]}`;
}
return phone
回答by mikryz
I'm using this function to format US numbers.
我正在使用此函数来格式化美国数字。
function formatUsPhone(phone) {
var phoneTest = new RegExp(/^((\+1)|1)? ?\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})( ?(ext\.? ?|x)(\d*))?$/);
phone = phone.trim();
var results = phoneTest.exec(phone);
if (results !== null && results.length > 8) {
return "(" + results[3] + ") " + results[4] + "-" + results[5] + (typeof results[8] !== "undefined" ? " x" + results[8] : "");
}
else {
return phone;
}
}
It accepts almost all imaginable ways of writing a US phone number. The result is formatted to a standard form of (987) 654-3210 x123
它接受几乎所有可以想象的写美国电话号码的方式。结果被格式化为 (987) 654-3210 x123 的标准格式
回答by Jason Sebring
thinking backwards
倒退思考
Take the last digits only (up to 10) ignoring first "1".
仅取最后一位数字(最多 10 位)而忽略第一个“1”。
function formatUSNumber(entry = '') {
const match = entry
.replace(/\D+/g, '').replace(/^1/, '')
.match(/([^\d]*\d[^\d]*){1,10}$/)[0]
const part1 = match.length > 2 ? `(${match.substring(0,3)})` : match
const part2 = match.length > 3 ? ` ${match.substring(3, 6)}` : ''
const part3 = match.length > 6 ? `-${match.substring(6, 10)}` : ''
return `${part1}${part2}${part3}`
}
example input / output as you type
键入时的示例输入/输出
formatUSNumber('+1333')
// (333)
formatUSNumber('333')
// (333)
formatUSNumber('333444')
// (333) 444
formatUSNumber('3334445555')
// (333) 444-5555
回答by Alex Turpin
var numbers = "(123) 456-7890".replace(/[^\d]/g, ""); //This strips all characters that aren't digits
if (numbers.length != 10) //wrong format
//handle error
var phone = "(" + numbers.substr(0, 3) + ") " + numbers.substr(3, 3) + "-" + numbers.substr(6); //Create format with substrings
回答by jjones
Here is one that will accept both phone numbers and phone numbers with extensions.
这是一个同时接受电话号码和带分机号码的电话号码。
function phoneNumber(tel) {
var toString = String(tel),
phoneNumber = toString.replace(/[^0-9]/g, ""),
countArrayStr = phoneNumber.split(""),
numberVar = countArrayStr.length,
closeStr = countArrayStr.join("");
if (numberVar == 10) {
var phone = closeStr.replace(/(\d{3})(\d{3})(\d{4})/, ".."); // Change number symbols here for numbers 10 digits in length. Just change the periods to what ever is needed.
} else if (numberVar > 10) {
var howMany = closeStr.length,
subtract = (10 - howMany),
phoneBeginning = closeStr.slice(0, subtract),
phoneExtention = closeStr.slice(subtract),
disX = "x", // Change the extension symbol here
phoneBeginningReplace = phoneBeginning.replace(/(\d{3})(\d{3})(\d{4})/, ".."), // Change number symbols here for numbers greater than 10 digits in length. Just change the periods and to what ever is needed.
array = [phoneBeginningReplace, disX, phoneExtention],
afterarray = array.splice(1, 0, " "),
phone = array.join("");
} else {
var phone = "invalid number US number";
}
return phone;
}
phoneNumber("1234567891"); // Your phone number here
回答by Rodnier Borrego Clavero
You can use this functions to check valid phone numbers and normalize them:
您可以使用此功能来检查有效的电话号码并将其标准化:
let formatPhone = (dirtyNumber) => {
return dirtyNumber.replace(/\D+/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '() -');
}
let isPhone = (phone) => {
//normalize string and remove all unnecessary characters
phone = phone.replace(/\D+/g, '');
return phone.length == 10? true : false;
}
回答by Jeremy
I've extended David Baucum's answerto include support for extensions up to 4 digits in length. It also includes the parentheses requested in the original question. This formatting will work as you type in the field.
我已经扩展了David Baucum 的答案,以支持最多 4 位数字的扩展。它还包括原始问题中要求的括号。当您在字段中键入时,此格式将起作用。
phone = phone.replace(/\D/g, '');
const match = phone.match(/^(\d{1,3})(\d{0,3})(\d{0,4})(\d{0,4})$/);
if (match) {
phone = `(${match[1]}${match[2] ? ') ' : ''}${match[2]}${match[3] ? '-' : ''}${match[3]}${match[4] ? ' x' : ''}${match[4]}`;
}
return phone;