Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

492
Visualizações
Regex - How to replace a specific character in a string after being typed only once?

I'm trying to limit an input field to only numbers and the possibility of a "+" sign just at the string's [0] index. The idea is to let the user type their phone number, I have come up with this:

function main() {
  let phone = document.getElementById('phone');
  let phoneRegex = /[a-zA-Z]|[-!$%^&*()_|~=`{}[\]:";'<>?,./]/;
  phone.value = phone.value.replace(phoneRegex, '');

  console.log(phone.value);
}
<input id="phone">
<button onclick="main()">Run</button>

The thing is, this works fine, but I want to limit the first character to only a digit or a "+" sign, characters coming from index [1] and on should only be numbers.

I can't come up with an idea on how to solve this

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try this as a starting point (you'll probably want to expand it further to account for total string length, delimiters like -, etc.):

let phoneRegex = /\+?\d+/;

+ in a regular expression has a special meaning, so when we want to match the literal character "+" then we need to escape it. And following it with the ? character makes it optional:

\+?

Next, \d followed by + will match any sequence of one or more digits:

\d+

You can see a visualization of this pattern here.

about 4 years ago · Juan Pablo Isaza Relatório

0

I know I'm late in this game, but adding one more solution for me and other's future references.

I came up with this solution which works for me:

/^(\+|[0-9])?[0-9]{12}$/

Thanks

about 4 years ago · Juan Pablo Isaza Relatório

0

I want to limit the first character to only a digit or a "+" sign, characters coming from index [1] and on should only be numbers.

The regex:

/^\+?\d+$/

means:

From the beginning, one or zero + signs, then one or more numbers until the end.

Note the following regex symbols:

  • * - zero or more
  • + - one or more
  • ? - zero or one
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda