Home > Enterprise >  Regex - How to replace a specific character in a string after being typed only once?
Regex - How to replace a specific character in a string after being typed only once?

Time:10-19

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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.

CodePudding user response:

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
  • Related