Pesquisa de site

regex - Expressão Regular para reformatar um número de telefone dos EUA em Javascript


Estou procurando reformatar (substituir, não validar - existem muitas referências para validar) um número de telefone para exibição em Javascript. Aqui está um exemplo de alguns dos dados:

  • 123 4567890
  • (123) 456-7890
  • (123)456-7890
  • 123 456 7890
  • 123.456.7890
  • (em branco/nulo)
  • 1234567890

Existe uma maneira fácil de usar uma expressão regular para fazer isso? Estou procurando a melhor maneira de fazer isso. Existe uma maneira melhor?

Quero reformatar o número para o seguinte: (123) 456-7890

Resposta #1

Assumindo que você queira o formato "(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;
}

Aqui está uma versão que permite o código internacional opcional +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"

Resposta #2

var x = '301.474.4062';
    
x = x.replace(/\D+/g, '')
     .replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');

alert(x);

Resposta #3

Solução possível:

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})/, "($1) $2-$3");
    }

    return null;
}

var phone = '(123)4567890';
phone = normalize(phone); //(123) 456-7890

Resposta #4

Esta resposta se baseia na resposta de maerics. Ela difere principalmente no fato de aceitar números de telefone parcialmente inseridos e formatar as partes que foram digitadas.

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

Artigos relacionados